python - 上一个问题 PySide2 QListView 和 QTableView 的新功能

标签 python qtableview pyside2 qstandarditemmodel

上一个问题是this .

编辑以提供信息:

该模型表示一个字典的字典,它们可以继承除键值对之外的其他字典:

dict_of_dicts={
'dict1':{'k1':'v1', 'k2':'v2', 'k3':'v3', 'EXISTING_DICT':'dict2'},
'dict2':{'k4':'v4'},
'dict3':{'k5':'v5', 'k6':'v6'},
}

成为qlistview:

*dict1
------
dict2
-----
dict3

以及在qlistview中选择dict1的qtableview:

k1 | v1
-------
k2 | v2
-------
k3 | v3
-------
dict2

有没有办法对模型进行排序,首先将继承的字典放在顶部,然后是字典元素?

dict2
-------
k1 | v1
-------
k2 | v2
-------
k3 | v3

如果我们在动态中引入新元素(我有办法在界面中引入新元素),那么无论顺序如何它都会排序?

我正在使用 QStandardItemModel 排序和 setSortRole(Qt.CheckStateRole)

最佳答案

使用我的 previous answer作为基础,有必要使用QSortFilterProxyModel,但我们必须使用角色QtCore.Qt.UserRole + 1000,此外我们必须修改我将指出的部分发表评论:

# ...

class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)
        model = create_model_from_dict(dict_of_dicts, self)

        self.tableview = TableView()
        self.proxy_model = QtCore.QSortFilterProxyModel() # <---
        self.proxy_model.setSourceModel(model) # <---
        self.proxy_model.setSortRole(QtCore.Qt.UserRole + 1000) # <---
        self.proxy_model.sort(0, QtCore.Qt.AscendingOrder) # <---
        self.tableview.setModel(self.proxy_model) # <---
        self.tableview.leftDoubleClicked.connect(self.handleSelectionChangedTV)

        # ...

    @QtCore.Slot(QtCore.QItemSelection)
    def handleSelectionChangedLV(self, item):
        ixs = item.indexes()
        if ixs:
            pix = self.proxy_model.mapFromSource(ixs[0]) # <---
            self.tableview.setRootIndex(pix) # <---
            model = self.tableview.model()
            self.tableview.clearSpans()
            for r in range(model.rowCount(self.tableview.rootIndex())):
                index = model.index(r, 0, self.tableview.rootIndex())
                if index.data(QtCore.Qt.UserRole + 1000):
                    self.tableview.setSpan(r, 0, 1, 2)

# ...

关于python - 上一个问题 PySide2 QListView 和 QTableView 的新功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54301406/

相关文章:

c++ - QTableView并设置指针位置

python - 如何访问 PySide2 中选中的 QCheckBox?

python - 通过比较两个数据帧获取唯一行

python - 用列表中的索引替换数组中的值

python - 从 StringIO 读取而不重置位置

python - CNN 模型训练 - 资源耗尽(Python 和 Tensorflow)

qt - 如何从 QHeaderView 中删除水平边框

python - 在 QAbstractItemModel 中不区分大小写排序

python - 如何在 QWidget 中居中背景图像

python - 如何在 PySide2 中将 python 列表转换为 QVariantList