如何突出显示 QTreeWidgetItem 文本

How to highlight QTreeWidgetItem text

单击按钮时,我需要使树项目高亮显示(编辑模式)(见下图)。目前我必须双击该项目才能将其设置为突出显示模式。如何实现?

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

class Dialog(QtGui.QDialog):
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)
        self.setLayout(QtGui.QVBoxLayout())
        tree = QtGui.QTreeWidget()
        self.layout().addWidget(tree)
        button = QtGui.QPushButton()
        button.setText('Add Item')
        self.layout().addWidget(button)
        button.clicked.connect(self.onClick)

        item = QtGui.QTreeWidgetItem()
        item.setFlags(item.flags() | QtCore.Qt.ItemIsEditable)
        item.setText(0, 'Item number 1')
        tree.addTopLevelItem(item)

    def onClick(self):
        print 'onClick'

dialog=Dialog()
dialog.show()
app.exec_()

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

class ItemDelegate(QtGui.QItemDelegate):
    def __init__(self, parent):
        QtGui.QItemDelegate.__init__(self, parent)

    def createEditor(self, parent, option, index):
        if not index: return
        line = QtGui.QLineEdit(parent)
        line.setText('Please enter the ')
        # line.selectAll()
        line.setSelection(0, len(line.text()))
        line.setFocus()
        return line

class Dialog(QtGui.QDialog):
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)
        self.setLayout(QtGui.QVBoxLayout())
        self.tree = QtGui.QTreeWidget()
        self.layout().addWidget(self.tree)
        button = QtGui.QPushButton()
        button.setText('Add Item')
        self.layout().addWidget(button)
        button.clicked.connect(self.onClick)
        self.tree.setColumnCount(3)

        delegate=ItemDelegate(self)
        self.tree.setItemDelegate(delegate)

        for row in range(5):
            rootItem = QtGui.QTreeWidgetItem()
            self.tree.addTopLevelItem(rootItem)
            for column in range(3):
                rootItem.setText(column, 'Root %s row %s'%(row, column))

            for child_number in range(2):
                childItem = QtGui.QTreeWidgetItem(rootItem)

                for col in range(3):
                    childItem.setText(col, 'Child %s row %s'%(child_number, col))

    def onClick(self):
        rootItem = QtGui.QTreeWidgetItem()
        rootItem.setText(0, 'New Item')
        rootItem.setFlags(rootItem.flags() | QtCore.Qt.ItemIsEditable)
        self.tree.addTopLevelItem(rootItem)
        self.tree.openPersistentEditor(rootItem, 0)
        rootItem.setSelected(True)


dialog=Dialog()
dialog.show()
app.exec_()