2

I've got a QTreeWidget item and the signal CurrentItemChanged connected to a method that updates the GUI based on a DB lookup.

The CurrentItemChanged documentation says it will pass QTreeWidgetItems as arguments to the method. First the current item, then the item that had been selected previously.

I am seeing a QTreeWidgetItem followed by an integer, probably the column of the currently selected item, getting passed instead. This behavior does not seem to be part of anyone's documentation for Pyqt5.

Before I go storing references to the previous Item myself, is there something I am missing? The code is depressingly simple:

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

def update(self, old, new):
    # do stuff with old and new, both as as QTreeWidgetItems
bythenumbers
  • 155
  • 1
  • 3
  • 10

1 Answers1

4

This signal is emitted when the current item changes. The current item is specified by current, and this replaces the previous current item.

Try it:

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

S. Nick
  • 12,879
  • 8
  • 25
  • 33
  • This is another way of doing it, though really, it was my keyboard-chair interface having issues. Over-six-months-ago me is not as bright as he thinks he is. What really helped was having the right signal hooked up to begin with. – bythenumbers Jul 16 '18 at 21:51