答案 0 :(得分:0)
子类QTreeWidgetItem
。定义setData
方法以将值分配给属性_name
。
from PyQt4 import QtCore, QtGui
app = QtGui.QApplication([])
class TreeWidgetItem(QtGui.QTreeWidgetItem):
def __init__(self, parent=None):
super(TreeWidgetItem, self).__init__(parent)
def setData(self, column, role, value):
super(TreeWidgetItem, self).setData(column, role, value)
self._name = value.toString()
class Tree(QtGui.QTreeWidget):
def __init__(self, *args, **kwargs):
super(Tree, self).__init__()
for i, item_name in enumerate(['Item_1','Item_2','Item_3','Item_4','Item_5']):
rootItem = TreeWidgetItem(self)
rootItem.setFlags(rootItem.flags() | QtCore.Qt.ItemIsEditable)
rootItem._name = 'Root %s'%i
rootItem.setText(0, rootItem._name)
for number in range(3):
childItem = TreeWidgetItem(rootItem)
childItem.setFlags(rootItem.flags() | QtCore.Qt.ItemIsEditable)
childItem._name = 'Child %s'%number
childItem.setText(0, childItem._name)
self.addTopLevelItem(rootItem)
self.clicked.connect(self.onClick)
self.show()
def onClick(self, index):
print self.currentItem()._name