Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
985 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 Reply

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
  • ...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...