PDA

View Full Version : How to check un-check a checkbox when clicking on text



leinad
13th February 2020, 19:13
Hi,
I created a group of checkboxes in a combo box. It works fine, but I would also like to click on the text next to the check box besides the check box itself to check and uncheck the box.
Any ideas how to do it. Multiselect doesn't seem to do the trick.
QList<QStandardItem *> typeCheckBoxes;
QStringList typeNames;
QStandardItemModel *typeModel;
typeNames << "ujkkl" << "alkjbs" << "djklef" << "hijkl";
for(int i = 0; i < selectedNames.size(); i++)
{
typeCheckBoxes << new QStandardItem();
typeCheckBoxes[i]->setText(typeNames[i]);
typeModel->setItem(i, 0, typeCheckBoxes[i]);
typeCheckBoxes[i]->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled);
typeCheckBoxes[i]->setData(Qt::Checked, Qt::CheckStateRole);
typeCheckBoxes[i]->setCheckable(true);
}
Thanks in advance.

d_stranz
14th February 2020, 01:06
You could try connecting a slot to the QComboBox::activated() or QComboBox::currentIndexChanged() signal. In your slot, you look at the check state of the item at that index and flip it. However, I do not know how you can distinguish between a click on the text vs. a click on the checkbox. You might have to turn off the ItemIsUserCheckable flag and simply use the combobox signal to toggle the checkbox state.

leinad
14th February 2020, 15:09
Thanks, but unfortunately nothing happens when I click in the label, just the checkbox. I'll see if I can figure something else out.

d_stranz
14th February 2020, 17:07
unfortunately nothing happens when I click in the label

Sounds like the model is intercepting these signals and is eating them. The only other thing I can suggest is adding an event filter on the combobox to look for mouse press events (or better mouse press / release pairs), but then that gets ugly because you'd have to deal with the open / closed state of the drop-down, and if open, determining from a pixel mouse position which specific item was clicked.

Unlike QAbstractItemView, the combobox does not have any concept of a QItemSelectionModel (or at least it doesn't expose this in the public interface) so there is no way to interact with the selection state.