Qt:在数字字符串上使用QSortFilterProxyModel并获取错误的列文本时,排序是错误的 [英] Qt: Sorting is wrong when using QSortFilterProxyModel on number strings and getting wrong column text

查看:304
本文介绍了Qt:在数字字符串上使用QSortFilterProxyModel并获取错误的列文本时,排序是错误的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的模型视图treeview,它具有QSortFilterProxyModel代理,可以对列进行排序,并使用QStandardItemModel作为模型.
在每列中都有可以很好地排序的字符串,但是在包含数字(作为字符串)的列中排序是错误的.
说我有9,12,1(当我对它们进行排序时,每个数字在不同的列中得到1,12,9或12,1,9但从来没有按正确的顺序排列. 像1,9,12或12,9,1为什么?
我也注意到当我按列对行进行排序时,当我尝试使用m_model->item(iSelectedRow,0)->text();
来获取新的列文本时 我正在获取初始列文本,但从未获取新的排序列文本.为什么?

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 ?

推荐答案

这是因为默认情况下,QSortFilterProxyModel按DisplayRole排序.如果返回一个字符串,它将对该字符串进行排序. 要使模型按其他值排序,请在源模型中定义一个自定义排序角色,然后在代理上进行设置:

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 );

您的第二个问题:什么是m_model?源模型还是sortfilterproxy模型?前者从不通过排序进行更改,排序仅在代理中发生.

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.

这篇关于Qt:在数字字符串上使用QSortFilterProxyModel并获取错误的列文本时,排序是错误的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆