可编辑时如何编辑QTreeWidgetItem

How to edit QTreeWidgetItem when it is editable

当双击项目并且用户输入新的项目名称时,我希望将此文本值分配给打印 onClickitem._name 属性。如何做到这一点?

from PyQt4 import QtCore, QtGui
app = QtGui.QApplication([])

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 = QtGui.QTreeWidgetItem()
            rootItem.setFlags(rootItem.flags() | QtCore.Qt.ItemIsEditable)
            rootItem._name = 'Root %s'%i
            rootItem.setText(0, rootItem._name)      

            for number in range(3):
                childItem = QtGui.QTreeWidgetItem(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

tree=Tree()
app.exec_()

子类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