18

In my form I have a QListWidget which contains checkable QListWidgetItems. I'm looking for a way to capture the event of a QListWidgetItem being checked/unchecked. I don't see any such signal existing for this but maybe I'm wrong. What I'm currently doing is using the QListWidget::itemClicked() signal and checking the checkState of the QListWidgetItem, but this isn't what I want because this event happens any time the item is clicked, not just went the checkmark is toggled. Can anyone give some assistance? Thanks!

273K
  • 29,503
  • 10
  • 41
  • 64
Joseph
  • 12,678
  • 19
  • 76
  • 115
  • 1
    I think I can get around this using the QListWidget::itemChanged() signal, which is triggered when I check/uncheck an item, but it would also be triggered if I edit the value of the item which, although I'm not doing now, is still an imperfect solution. – Joseph Nov 23 '10 at 05:30
  • 1
    Another problem with `QListWidget::itemClicked()` is that it doesn't fire when you use keyboard, e.g use the Space key to change the checked state. – Hossein Mar 22 '13 at 11:30

2 Answers2

29

Apparently no such signal is provided, your best bet is to use QListWidget::itemChanged(QListWidgetItem* item) , and scan the resulting item->checkState(). This should be a slight improvement over using itemClicked

Daniel Vérité
  • 58,074
  • 15
  • 129
  • 156
jkerian
  • 16,497
  • 3
  • 46
  • 59
  • It is a protected Signal. I will face an error when I use this error as explained [here](https://stackoverflow.com/q/48059796/1080355). – VSB Jan 02 '18 at 11:10
  • 1
    itemChanged doesn't always fire; e.g. if you highlight the item, and press the spacebar repeatedly. – CodeLurker Sep 28 '18 at 18:12
  • 1
    @CodeLurker: That sounds like a bug. – jkerian Oct 01 '18 at 16:17
  • 3
    I was mistaken. itemChanged() is indeed the right signal to intercept. It _does_ fire when the checkstate changes. Be sure not to confuse it with currentItemChanged(), which does not. – CodeLurker Jan 19 '20 at 20:00
1

An extra option is to use your own QAbstractListModel with a QListView. At first this does add some extra code as you need to add your own management code . But you do get a lower level access. Basically because the QListView will ask your model what to do. It will also relay input back to your listmodel where you can hook into it.

Alternatively you could subclass QStandardItemModel and catch certain edits related to changing the checkbox.

Daniël Sonck
  • 869
  • 7
  • 9