【发布时间】:2015-02-03 04:13:04
【问题描述】:
短版
我正在尝试在QTreeView 中显示来自QAbstracctTableModel 的数据。当我这样做时,我最终将 整个表 显示为每个节点的子节点(以及孙子节点,等等)。如何显示抽象表模型的树视图?
详情
我正在尝试在QAbstractTableModel 中显示QTreeView 中的一些数据。在Model-View Tutorial 中,在展示了一个示例QAbstractTableModel 之后,它看起来就像用QTreeView 替换QTableView 一样简单:
您可以将上面的示例转换为带有树的应用程序 看法。 只需将 QTableView 替换为 QTreeView,结果是 读/写树。无需对模型进行任何更改。
当我进行这个替换时,我最终会显示一个树,但是如果我单击任何图标来展开它(这应该什么都不做,因为没有内置层次结构),Python 会崩溃并显示 @987654332 @。这个has been brought up before ],但没有可行的解决方案。
为了尝试解决此问题,我在QAbstractTableModel 子类中重新实现了索引函数(请参阅下面的完整工作示例)。这导致了一种非常不同类型的错误。也就是说,树中的每个节点现在都包含整个表作为数据。无论我点击多少次,整个表格都会显示出来。像这样:
我似乎陷入了某种递归的噩梦,不知道如何逃脱。下面的相关问题表明我可能不得不去QAbstractItemModel,但上面的教程引用却暗示了其他情况(其中指出,不必对模型进行任何更改)。
相关问题
QTreeView always displaying the same data
完整的工作示例
from PySide import QtGui, QtCore
class Food(object):
def __init__(self, name, shortDescription, note, parent = None):
self.data = (name, shortDescription, note);
self.parentIndex = parent
class FavoritesTableModel(QtCore.QAbstractTableModel):
def __init__(self):
QtCore.QAbstractTableModel.__init__(self)
self.foods = []
self.loadData()
def data(self, index, role = QtCore.Qt.DisplayRole):
if role == QtCore.Qt.DisplayRole:
return self.foods[index.row()].data[index.column()]
return None
def rowCount(self, index=QtCore.QModelIndex()):
return len(self.foods)
def columnCount(self, index=QtCore.QModelIndex()):
return 3
def index(self, row, column, parent = QtCore.QModelIndex()):
return self.createIndex(row, column, parent)
def loadData(self):
allFoods=("Apples", "Pears", "Grapes", "Cookies", "Stinkberries")
allDescs = ("Red", "Green", "Purple", "Yummy", "Huh?")
allNotes = ("Bought recently", "Kind of delicious", "Weird wine grapes",
"So good...eat with milk", "Don't put in your nose")
for name, shortDescription, note in zip(allFoods, allDescs, allNotes):
food = Food(name, shortDescription, note)
self.foods.append(food)
def main():
import sys
app = QtGui.QApplication(sys.argv)
model = FavoritesTableModel()
#Table view
view1 = QtGui.QTableView()
view1.setModel(model)
view1.show()
#Tree view
view2 = QtGui.QTreeView()
view2.setModel(model)
view2.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
【问题讨论】: