3
votes

You can toggle a QCheckBox by clicking on the label string. This gives the user a comfortably large target to click.

However, if I have a QListWidget with checkable items, the user must click inside the little box to toggle the item. This makes checking the items tedious and even a little painful for those of us with a Repetitive Stress Injury.

I tried connecting to the QListWidget itemClicked signal and toggling the item check box. That works fine if the user clicks on the item text. But if they actually click on the box, the check state gets toggled, then the itemClicked signal is sent, and code toggles the check state back to where it was.

Can anyone suggest a way to toggle the check state by clicking on either the checkbox or the item text?

Thanks...

3

3 Answers

1
votes

QListWidgetItem doesn't provide any way to know where did user click, label or box, so the easiest way is to use QCheckBox as a widget. Now QCheckBox will behave as QCheckBox and user will be able to check box by clicking everywhere (on QCheckBox)

for(int r=0;r<7;r++)
{
    QListWidgetItem* lwi = new QListWidgetItem;
    ui->listWidget->addItem(lwi);
    ui->listWidget->setItemWidget(lwi, new QCheckBox(QString("checkBox%1").arg(r)));
}

Disadvantage: it can reduce performance if you have lot of items.

1
votes

You can just keep the flag Qt::ItemIsUserCheckable unset and then the item's check state won't change when the checkbox gets clicked on. When then the itemClicked signal of the QListWidget is connected to a slot that toggles the check state the check state won't get toggled twice anymore.

The checkboxes of the items are shown when the item has a check state set no matter if they are checkable by the user.

1
votes

Here is the solution using python.

    listwidget.itemPressed["QListWidgetItem*"].connect(
        lambda item: item.setCheckState(
           Qt.Checked
            if item.checkState() == Qt.Unchecked
            else Qt.Unchecked
        )
    )

Declaring this, before setting up your QlistWidget, or before adding your QlistWidget items seems to work well, and allows for an easy way to change the checkState of the default listWidget items.