如何使用基于组合框选择的 QSortFilterProxyModel 对 TreeView 项目进行排序

How to sort TreeView Items using QSortFilterProxyModel based on Combobox Selection

我的应用程序中有一个 TreeView。我使用从 QSortFilterProxyModel 继承的 class 限制显示的行。我还需要根据组合框的 selectedIndex 对 TreeView 中的项目进行排序。 到目前为止我所做的是:

  1. 当组合框的selected Index发生变化时,我会调用继承自QSortFilterProxyModel的class中的函数调用sort(0)函数
  2. 在继承自QSortFilterProxyModel的class中,我重写了lessThan函数,并根据ComboBox
  3. 中当前的selection实现了我的逻辑

问题是,排序并不总是发生。当我 运行 应用程序并在组合框中选择一个项目时,树项目得到正确排序。但是如果我 select 组合框中的另一个项目,树将不会更新。不过 lessThan 函数会被调用!

如果您的代理设置为动态 sort/filter,这很可能是这样,那么再次使用相同的列和排序方向调用 sort() 将不会执行任何操作。 参见 https://code.woboq.org/qt5/qtbase/src/corelib/itemmodels/qsortfilterproxymodel.cpp.html#_ZN21QSortFilterProxyModel4sortEiN2Qt9SortOrderE

您将 also/alternatively 必须调用 QSortFilterProxyModel::invalidate() 来触发恢复。