Qt: Sorting is wrong when using QSortFilterProxyModel on number strings and getting wrong column text

后端 未结 3 658
梦如初夏
梦如初夏 2021-01-06 19:19

i have simple model view treeview with QSortFilterProxyModel proxy to sort the columns and QStandardItemModel as the model
in each columns there are string that gets sor

相关标签:
3条回答
  • 2021-01-06 19:47

    That's because by default, QSortFilterProxyModel sorts by DisplayRole. If that returns a string, it will sort the string. To have the model sort by some other value, define a custom sort role in the source model and set it on the proxy:

    class MyModel {
       ...
       enum Role {
          SortRole=Qt::UserRole
       };
       QVariant data( ... ) const {
           ...
           switch ( role ) {
           case Qt::DisplayRole:
               return value as string;
           case SortRole:
               return value as int;
           }
       }
    };
    
    ...
    sortfilterproxy->setSortRole( MyModel::SortRole );
    

    Your second question: What is m_model? The source model, or the sortfilterproxymodel? The former is never changed by sorting, the sorting happens only in the proxy.

    0 讨论(0)
  • 2021-01-06 19:48

    use QStandardItem::setData() when filling your table as shown below. Then all will work as expected.

    below lines from Qt documentation

    virtual void QStandardItem::setData(const QVariant & value, int role = Qt::UserRole + 1)
    

    Here is simple usage of set data.

    item->setData(intData, Qt::DisplayRole);
    
    0 讨论(0)
  • 2021-01-06 19:50

    If you sort the strings "9", "12" and "1" you will get "1", "12", "9" (lexicographic sorting). If you want them sorted as numbers, you have to subclass the QSortFilterProxyModel and reimplement the lessThan member function where you could just use QString::toInt().

    You can find out all of this by studying the excelent Qt documentation, where you also find information about mapToSource(), mapFromSource(), mapSelectionToSource(), and mapSelectionFromSource() to convert source QModelIndexes to sorted/filtered model indexes or vice versa.

    0 讨论(0)
提交回复
热议问题