dte*_*ech 6 sorting qt qml qabstractlistmodel qsortfilterproxymodel
我已经基于底层QHash创建了一个QAbstractListModel派生模型.由于我需要在QML中使用该模型,我无法利用Qt小部件和视图集成的排序功能.
我尝试使用QSortFilterProxyModel但它似乎不适用于我的模型.让模型在QML中正常工作并不够乏味,现在我仍然坚持排序.
任何建议表示赞赏.
这是模型来源:
typedef QHash<QString, uint> Data;
class NewModel : public QAbstractListModel {
Q_OBJECT
Q_PROPERTY(int count READ count NOTIFY countChanged)
public:
NewModel(QObject * parent = 0) : QAbstractListModel(parent) {}
enum Roles {WordRole = Qt::UserRole, CountRole};
QHash<int, QByteArray> roleNames() const {
QHash<int, QByteArray> roles;
roles[WordRole] = "word";
roles[CountRole] = "count";
return roles;
}
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const {
if (index.row() < 0 || index.row() >= m_data.size()) return QVariant();
Data::const_iterator iter = m_data.constBegin() + index.row();
switch (role) {
case WordRole:
return iter.key();
case CountRole:
return iter.value();
} return QVariant();
}
int rowCount(const QModelIndex &parent) const {
Q_UNUSED(parent)
return m_data.size();
}
int count() const { return m_data.size(); }
public slots:
void append(const QString &word) {
bool alreadyThere = m_data.contains(word);
if (alreadyThere) m_data[word]++;
else m_data.insert(word, 1);
Data::const_iterator iter = m_data.find(word);
uint position = delta(iter);
if (alreadyThere) {
QModelIndex index = createIndex(position, 0);
emit dataChanged(index, index);
} else {
beginInsertRows(QModelIndex(), position, position);
endInsertRows();
emit countChanged();
}
}
void prepend(const QString &word) {
if (m_data.contains(word)) m_data[word]++;
else m_data.insert(word, 1);
}
signals:
void countChanged();
private:
uint delta(Data::const_iterator i) {
uint d = 0;
while (i != m_data.constBegin()) { ++d; --i; }
return d;
}
Data m_data;
};
Run Code Online (Sandbox Code Playgroud)
这是"试图"对它进行排序:
NewModel model;
QAbstractItemModel * pm = qobject_cast<QAbstractItemModel *>(&model);
QSortFilterProxyModel proxy;
proxy.setSourceModel(pm);
proxy.setSortRole(NewModel::WordRole);
proxy.setDynamicSortFilter(true);
Run Code Online (Sandbox Code Playgroud)
唉,代理作为模型工作,但它不对条目进行排序.
小智 6
如果启用QSortFilterProxyModel :: setDynamicSortFilter(true),则需要调用QSortFilterProxyModel :: sort(...)函数一次,让代理知道要排序的方式.
有了它,只要模型更新,代理就会自动对所有内容进行排序.
proxy.setDynamicSortFilter(true);
proxy.sort(0);
Run Code Online (Sandbox Code Playgroud)
首先,不需要qobject_cast<QAbstractItemModel *>向下转型——它NewModel是 的派生类,QAbstractItemModel并且多态性原则表明您可以在父类适用的任何地方使用子类。
其次,您的prepend方法不使用beginInsertRowsand endInsertRows。这违反了 MVC API。如果您以这种方式使用它,则会在附加视图和代理模型中出现数据损坏。
第三,您没有提到您是否实际上使用代理模型作为附加视图的模型:)。
最后,您将用作QHash数据的后备存储以QHash::iterator进行插入。这是一个令人兴奋的解决方案,但无法正常工作——插入或删除可能会导致哈希表增长/收缩,这意味着更改您通过模型索引发布的所有数据。这是行不通的。QHash当您需要稳定订单时请勿使用。O(n)您的方法的复杂性应delta被解释为警告;这是错误的做法。