如何在可编辑的情况下编辑QTreeWidgetItem

时间:2016-05-27 03:32:38

标签: python qt pyqt qtreewidget qtreewidgetitem

enter image description here

当双击该项目并且用户输入新项目名称时,我希望将此文本值分配给打印item._name的{​​{1}}属性。怎么做到这一点?

onClick

1 个答案:

答案 0 :(得分:0)

enter image description here

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