Search code examples
qtpyqtpysideqlistwidget

qt listwidget clear() unexpectedly trigger itemSelectionChanged()


in PyQt(Pyside6), I created a QListWidget:

  • it shows 3 items of '1/2/3' when I click one 'show_123' Button
  • it shows 3 items of 'a/b/c' when I click one 'show_abc' Button
  • when I click '1' in the QListWidget, one Label shows '1'; click '2', shows '2'; click 'a' show 'a', etc

the 'show_abc' button simple code is as bellow, ('show_123' is similar)

listWidget1.clear()
listWidget1.addItems(['a','b','c'])

and pseudo code for updating Label is

listWidget1.itemSelectionChanged.connect(update_label)

BUT, I found the "listWidget1.clear()" will trigger "listWidget1.itemSelectionChanged", so to call update_label. This is unexpected, I just want to 'clear&addItems' to refresh. how could I solve this problem


Solution

  • I added "setCurrentItem(None)" before clear() to solve it, not found some more elegant way.

    listWidget1.setCurrentItem(None)
    listWidget1.clear()
    listWidget1.addItems(...)