python - 将 QAbstractTableModel 与 QTreeView 一起使用时崩溃

标签 python qt pyqt

既然看起来没有专门为QTreeView“设计”的“专用”抽象模型(对于QListView,有QAbstractListModel,对于QTableView,有QAbstractTableModel),并且由于我需要能够显示标题,所以我选择使用 Table 的抽象模型:QAbstractTableModel 和“QTreeView”。代码运行良好,但如果单击加号,它会立即崩溃。 QAbstractTableModel 不应该与“QTreeView”一起使用吗?使用什么抽象模型?

enter image description here

import os,sys
from PyQt4 import QtCore, QtGui
app=QtGui.QApplication(sys.argv)
elements={'Animals':{1:'Bison',2:'Panther',3:'Elephant'},'Birds':{1:'Duck',2:'Hawk',3:'Pigeon'},'Fish':{1:'Shark',2:'Salmon',3:'Piranha'}}

class Model(QtCore.QAbstractTableModel):
    def __init__(self):
        QtCore.QAbstractListModel.__init__(self)
        self.items=[] 
        self.modelDict={}
    def rowCount(self, parent=QtCore.QModelIndex()):
        return len(self.items)   
    def columnCount(self, index=QtCore.QModelIndex()):
        return 3
    def data(self, index, role):
        if not index.isValid() or not (0<=index.row()<len(self.items)): return QtCore.QVariant()
        if role==QtCore.Qt.DisplayRole:          return QtCore.QVariant(self.items[index.row()])
    def buildItems(self):
        totalItems=self.rowCount()
        for key in self.modelDict:    
            self.beginInsertRows(QtCore.QModelIndex(), totalItems+1, 0)
            self.items.append(key)
            self.endInsertRows()

class TreeView(QtGui.QTreeView):
    def __init__(self):
        super(TreeView, self).__init__()
        self.model= Model()
        self.model.modelDict=elements
        self.model.buildItems()
        self.setModel(self.model)
        self.show()       

window=TreeView()
sys.exit(app.exec_())

最佳答案

您无法将 QAbstractTableModelQTreeView 一起正确使用,因为该类仅适用于 QTableView。您必须继承 QAbstractItemModel ,(这是 QAbstractTableModelQAbstractListModel 继承的),并实现 index()parent()rowCount()columnCount()data(),如 subclassing 中所述。 Qt 精美手册的一部分。对于 QTreeView 来说,parent() 特别需要注意,因为它告诉 QTreeView 某个项目是否位于顶部级别或者它是否是树中另一个项目的子项。

我相信 Qt 中没有 QAbstractTreeModel 类的主要动机是因为您需要重写所有这些方法来创建一个具有适当表达能力的树模型。

关于python - 将 QAbstractTableModel 与 QTreeView 一起使用时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25880629/

相关文章:

python - 'QThread : Destroyed while thread is still running' on quit

python - 禁止(CSRF token 丢失或不正确)Django 错误

python - 在 Python 中添加到自定义类

python - 欧拉计划第 36 题

c++ - Qt5 将字符转换为 8 位无符号值

python - PyQt4:重新排序 QDialogBu​​ttonBox 中的确定和取消按钮

python - qtreewidget 不需要的空白(额外的不可删除的行)

python - python doctest中的对象重用

c++ - 为什么Qt默认信号是公开的?

qt - 带有元组的 PySide/PyQT 信号和槽?