PyQt:动态地向TreeWidget添加子项

时间:2016-08-26 00:19:59

标签: python pyqt pyqt4 qtreewidget qtreewidgetitem

我有一个TreeWidget,其中包含一个或多个父项,每个父项都有可变数量的子项。最初填充树(例如,使用来自实际应用程序中的数据库的数据)。我希望用户能够为每个父级添加一个或多个子级,以及编辑当前选定的子级,但无法弄清楚如何使用它。

下面是我的示例代码,它使用父级和5个子级构建树。该表格拦截了" Return"和" Ins"键和调用简单的数据输入对话框,以获取要作为新子项输入的文本或编辑当前选定的子项。在这里我遇到了两个问题:首先,如何获取当前所选子项的文本进行编辑?第二,如何将输入文本作为新子项(在示例代码中,我只能在树的父级添加输入的文本)。

我一如既往地感谢您提供的任何帮助。

import sys
from PyQt4.QtCore import * 
from PyQt4.QtGui import *

class MyMainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MyMainWindow, self).__init__(parent)
        self.tree = QTreeWidget(self)
        insertKey = QShortcut(QKeySequence(Qt.Key_Insert), self.tree)
        self.connect(insertKey, SIGNAL("activated()"), self.itemInsert)
        editKey = QShortcut(QKeySequence(Qt.Key_Return), self.tree)
        self.connect(editKey, SIGNAL("activated()"), self.itemEdit)
        self.setCentralWidget(self.tree)
        self.tree.setHeaderLabel('Tree')
        i = QTreeWidgetItem(self.tree, ['Parent'])   
        self.tree.addTopLevelItem(i)
        for x in range(5):
            j = QTreeWidgetItem(i ,['Child {}'.format(x)])

    def itemInsert(self):
        text, ok = QInputDialog.getText(self, "Add Child", "Enter child name:")
        if ok and not text.isEmpty():
            child = QTreeWidgetItem(self.tree, [text])

    def itemEdit(self):
        pass

if __name__ == "__main__":
    app = QApplication(sys.argv)
    ui = MyMainWindow()
    ui.show()
    sys.exit(app.exec_()) 

1 个答案:

答案 0 :(得分:2)

要获取所选元素,我们使用返回所选元素的{your QTreeWidget}.selectedItems()函数。

在您的情况下,选择应该是模式:SingleSelection

import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *


class MyMainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MyMainWindow, self).__init__(parent)
        self.tree = QTreeWidget(self)

        self.tree.setSelectionMode(QAbstractItemView.SingleSelection)

        insertKey = QShortcut(QKeySequence(Qt.Key_Insert), self.tree)
        insertKey.activated.connect(self.itemInsert)
        editKey = QShortcut(QKeySequence(Qt.Key_Return), self.tree)
        editKey.activated.connect(self.itemEdit)
        self.setCentralWidget(self.tree)
        self.tree.setHeaderLabel('Tree')
        i = QTreeWidgetItem(self.tree, ['Parent'])
        self.tree.addTopLevelItem(i)
        for x in range(5):
            QTreeWidgetItem(i, ['Child {}'.format(x)])

    def itemInsert(self):
        text, ok = QInputDialog.getText(self, "Add Child", "Enter child name:")
        if ok and text != "":
            if len(self.tree.selectedItems()) > 0:
                QTreeWidgetItem(self.tree.selectedItems()[0], [text])
            else:
                QTreeWidgetItem(self.tree, [text])

    def itemEdit(self):
        if self.tree.selectedItems():
            item = self.tree.selectedItems()[0]
            text, ok = QInputDialog.getText(self, "Edit Child", "Modify name:", QLineEdit.Normal, item.text(0))
            if ok and text != "":
                item.setText(0, text)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    ui = MyMainWindow()
    ui.show()
    sys.exit(app.exec_())