Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
983 views
in Technique[技术] by (71.8m points)

qt - How to sort data in QTableWidget?

I have a QTableWidget and the first column contains numbers from 1 to 1000. Now I need to sort the table based on this first column.

I'm using the function sortItems(int column, Qt::AscendingOrder), but it is displayed as:

1, 10, 100, 1000, 101, 102, ...

Yet I need this result:

1, 2, 3 ,4...., 1000.

I'm using a CSV file for populating the table.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The values are sorted as strings because you stored them as such in the model.

The QVariant can remember the original type of the data if you let it do the conversion itself, and the comparison operator from that type will be used when sorting:

// Get the value from the CSV file as a numeric type
int valueFromCsvFile = ...;

// don't do this
QTableWidgetItem *item = new QTableWidgetItem(QString::number(valueFromCsvFile));

// but do this instead
QTableWidgetItem *item = new QTableWidgetItem;
item.setData(Qt::EditRole, valueFromCsvFile);    

The cell editor will also adapt to the type of the QVariant:

  • QSpinBox for int,
  • QDoubleSpinBox for double and float,
  • QDateTimeEdit for QDateTime
  • ...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...