在QTreeView上附加namedtuple数据

时间:2013-04-10 00:53:49

标签: python pyqt pyqt4

我正在尝试将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'的值)。谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

我最终使用了QTreeWidget并设置了这样的树项数据:

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

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

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