python - PyQt:动态向 TreeWidget 添加子项

标签 python pyqt pyqt4 qtreewidget qtreewidgetitem

我有一个带有一个或多个父级的 TreeWidget,每个父级都有可变数量的子级。该树最初是填充的(例如,使用来自实际应用程序中的数据库的数据)。我希望用户能够向每个父级添加一个或多个子级,以及编辑当前选定的子级,但不知道如何做到这一点。

下面是我的示例代码,它构建了一棵具有父级和五个子级的树。该表单拦截“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_()) 

最佳答案

为了获取所选元素,我们使用返回所选元素的{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_())

关于python - PyQt:动态向 TreeWidget 添加子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39156625/

相关文章:

python - 我想要三个已安装的 PyQt DLL 目录中的哪一个?

qt - QGridLayout 不返回其所有子部件

python - 为什么 `QtGui.QValidator.validate`的返回如此不一致?处理这个问题的可靠方法?

python - 如何通过解析导入来组合并获取单个 Python 文件

python tarfile错误: struct.错误:解包需要长度为4的字符串参数

python - 通过 h5py 在 hdf5 中进行 blosc 压缩

python - 如何让Qtextedit变成文本且不可选择?

python - 我在我的 pyqt5 程序中使用 QDoubleValidator 但它似乎不起作用

python - 如何在 PyQt4 中使用 setRowHeight 和 resizeRowToContents 调整行大小?

python - Django:避免服务器端和客户端验证代码重复