Pyqt5 QTreeWidget CurrentItemChanged信号发送整数作为前一项

时间:2018-07-16 19:43:05

标签: python pyqt pyqt5 qtreewidget qtreewidgetitem

我有一个QTreeWidget项目,信号CurrentItemChanged连接到了一种基于数据库查找更新GUI的方法。

CurrentItemChanged文档说它将把QTreeWidgetItems作为参数传递给方法。首先是当前项目,然后是先前已选择的项目。

我看到QTreeWidgetItem后面跟一个整数(可能是当前所选项目的列)被传递了。这种行为似乎不属于任何Pyqt5文档的一部分。

在我自己存储对上一个项目的引用之前,我缺少什么吗?该代码非常简单:

self.TreeWidget.currentItemChanged.connect(self.update) # signal connect

def update(self, old, new):
    # do stuff with old and new, both as as QTreeWidgetItems

1 个答案:

答案 0 :(得分:1)

  

当前项目更改时发出此信号。当前项目由current指定,它将替换先前的当前项目。

尝试一下:

import sys
from PyQt5 import QtWidgets, QtGui, QtCore

class Window(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)
        self.vlayout = QtWidgets.QVBoxLayout()

        # tree widget item
        tree_widget_item = QtWidgets.QTreeWidgetItem(['Item 1'])
        tree_widget_item.addChild(QtWidgets.QTreeWidgetItem(['Sub item 1']))  
        tree_widget_item.addChild(QtWidgets.QTreeWidgetItem(['Sub item 2']))

        # tree widget
        tree_widget = QtWidgets.QTreeWidget(self)
        tree_widget.addTopLevelItem(tree_widget_item)
        self.vlayout.addWidget(tree_widget)

        tree_widget.currentItemChanged.connect(self.current_item_changed)

    @QtCore.pyqtSlot(QtWidgets.QTreeWidgetItem, QtWidgets.QTreeWidgetItem)
    def current_item_changed(self, current, previous):
        print('\ncurrent: {}, \nprevious: {}'.format(current, previous))


application = QtWidgets.QApplication(sys.argv)
window = Window()
window.setWindowTitle('Tree widget')
window.resize(250, 180)
window.show()
sys.exit(application.exec_())

enter image description here