PyQt5 QtreeWidget:如何在QtreeWidgetItem中访问自定义窗口小部件的方法?

时间:2018-08-14 12:52:06

标签: python pyqt5 qtreewidgetitem

我有一个简单的QTreeWidget:

self.treeWidget = QTreeWidget(self)
col = ("Status", "Name")
self.treeWidget.setColumnCount(2)
self.treeWidget.setHeaderLabels(col)

我使用填充的女巫:

wid = Custom_Widget()
item = QTreeWidgetItem(self.treeWidget)
item.setText(1, "some string")
item.treeWidget().setItemWidget(item, 0, wid)

我可以通过使用

轻松地访问文本列:
root = self.treeWidget.invisibleRootItem()
it = root.child(2) # for example the third item
it.setText(1, "Edited")

我需要编辑第0列中的costum_widget,所以我如何访问它或调用他的方法?

1 个答案:

答案 0 :(得分:0)

我通过保留我创建的所有costum_widget的列表解决了该问题,我的代码将是:

from CustomWidgets import Custom_Widget
from PyQt5.QtWidgets import *
import sys


class MyExample(QWidget):

    def __init__(self):
        super().__init__()

        self.treeWidget = QTreeWidget(self)
        self.group_wid = []  # my list of widgets
        col = ("Status", "Name")
        self.treeWidget.setColumnCount(2)
        self.treeWidget.setHeaderLabels(col)

        self.populate_tree()
        self.edit_tree()
        self.show()

    def populate_tree(self):
        for i in range(10):
            wid = Custom_Widget()
            self.group_wid.append(wid)  # each time i instantiate a Custom_Widget i'll add it to my list of widgets
            item = QTreeWidgetItem(self.treeWidget)
            item.setText(1, "some string")
            item.treeWidget().setItemWidget(item, 0, wid)

    def edit_tree(self):
        root = self.treeWidget.invisibleRootItem()
        it = root.child(2)  # for example the third item
        it.setText(1, "Edited")
        self.group_wid[2].my_method()  # i can easily edit my widgets that are in the QTreeWidget


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MyExample()
    app.exec_()

猜猜QtreeWidgetItem仅包含对包含的窗口小部件的引用。