How to sort data in QTableWidget?

后端 未结 5 1680
星月不相逢
星月不相逢 2020-12-06 10:31

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 func

5条回答
  •  [愿得一人]
    2020-12-06 11:06

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

提交回复
热议问题