开发者

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

开发者 https://www.devze.com 2023-03-17 15:12 出处:网络
i have simple model view treeview with QSortFilterProxyModel proxy to sort the columns and QStandardItemModel as the model

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 sorted fine but in columns that contains number ( as strings ) the sorting wrong .

say i have 9,12,1 (each number in different column when i sort them im getting 1,12,9 or 12,1,9 but never in the right order . like 1,9,12 or 12,9,1 why ?

also i notice that when i sort row by column , when i try to get the new column text with m_model->item(iSelectedRow,0)->text();

im getting 开发者_如何学运维the initial column text but never the new sorted column text. why ?


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.


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号