0

我正在尝试将 namedtuple 对象的节点附加到 treeView 但我不确定如何将 QAbstractItem 子类化(如果这甚至是正确的方法)。我对 Python 还是很陌生,所以这让我很困惑。这是我的问题代码:

Exercise = namedtuple('Exercise','name html list')
e_list = []
for i in range(1,6,1):
    dummy_list = [1,2,3,'a','b','c']
    ntup = Exercise("exercise{0}".format(i),'html here',dummy_list)
    e_list.append(ntup)

for e in e_list:
    item = QtGui.QStandardItem(e) # gives error
    self.tree_model.appendRow(item) # doesnt execute

这是整个程序:

#!/usr/bin/env python
#-*- coding:utf-8 -*-

from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from collections import namedtuple

class MyWindow(QtGui.QWidget):
    def __init__(self, parent=None):
        super(MyWindow, self).__init__(parent)

        self.pushButton = QtGui.QPushButton(self)
        self.pushButton.setText("Test 1 - doesn't work")
        self.pushButton.clicked.connect(self.on_pushbutton)

        self.pushButton2 = QtGui.QPushButton(self)
        self.pushButton2.setText("Test 2 - works")
        self.pushButton2.clicked.connect(self.on_pushbutton2)

        self.treeView = QtGui.QTreeView(self)
        self.treeView.clicked[QModelIndex].connect(self.on_clickitem)

        self.tree_model = QtGui.QStandardItemModel()
        self.treeView.setModel(self.tree_model)

        self.layoutVertical = QtGui.QVBoxLayout(self)
        self.layoutVertical.addWidget(self.pushButton)
        self.layoutVertical.addWidget(self.pushButton2)
        self.layoutVertical.addWidget(self.treeView)

    def on_pushbutton(self):
        Exercise = namedtuple('Exercise','name html list')
        e_list = []
        for i in range(1,3,1):
            dummy_list = [1,2,3,'a','b','c']
            ntup = Exercise("exercise{}".format(i),'html here',dummy_list)
            e_list.append(ntup)

        for e in e_list:
            item = QtGui.QStandardItem(e) # gives error
            self.tree_model.appendRow(item) # never occurs

    def on_pushbutton2(self):
        txt = 'hello world'
        item = QtGui.QStandardItem(txt)
        self.tree_model.appendRow(item)

    def on_clickitem(self,index):
        item = self.tree_model.itemFromIndex(index) # doesn't work
        print "item name:",item.getName() # doesn't work
        print "item html:",item.getHtml() # doesn't work
        print "item list:",item.getList() # doesn't work



if __name__ == "__main__":
    import sys

    app = QtGui.QApplication(sys.argv)
    app.setApplicationName('MyWindow')

    main = MyWindow()
    main.show()

    sys.exit(app.exec_())

我想将节点附加到树中,当我单击一个项目时,我想获取 namedtuple 的值(即“name”、“html”和“alist”的值)。谢谢你的帮助。

保罗

4

1 回答 1

0

我刚刚结束了使用 QTreeWidget 并像这样设置树项数据:

item = QtGui.QTreeWidgetItem()
item.mydata = my_namedtuple

我在这里找到了答案:QtGui QTreeWidgetItem setData holding a float number

我不知道你可以动态地为树项创建一个属性。

于 2013-04-11T06:21:24.123 回答