PDA

View Full Version : How do I tell when a QListWidgetItem is checked?



grabalon
3rd August 2010, 22:44
I am using the following code to create QListWidgetItems:

QListWidgetItem* newItem = new QListWidgetItem();
newItem->setText("Item");
newItem->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled | Qt::ItemIsSelectable);
newItem->setCheckState(Qt::Unchecked);
ui.listImages->addItem(newItem);

I now want to do something like:

connect(newItem, SIGNAL(toggled(bool)), this, SLOT(handleItemToggle(bool)));
The problem is that QListWidgetItem does not expose ANY signals, and none of the of the QListWidget signals appear to have anything to do with check marks. Any ideas?

Thanks!:eek:

bmhautz
3rd August 2010, 23:31
QListWidget does seem to offer the itemClicked and itemPressed signals. You could connect one of these signals to your slot and then check the items clicked state with QListWidgetItem's checkState function. Based on the check state, you could then do whatever you were going to do with the item.

Any sophisticated behavior beyond that may require you to code up an actual model though.

Hope that helps (and works - I normally use the model/view interface instead of the convenience widgets).

(EDIT) Note: Since changing the check state of an item requires a mouse click, it seems convenient to tie it to the itemClicked (or Pressed) signals which are provided. It seems hackish, but when that's all you've got to work with... :) Otherwise, you would have to set up some sort of polling function based on a timer to check all of the items' check states, and that seems to be a lot of work.

Lykurg
4th August 2010, 05:24
QListWidgetItem does not have any signal at all! You have to use the signal QListWidget::itemChanged() and check there if your item is checked or unchecked.

grabalon
4th August 2010, 20:32
Posted for the benefit of future readers:
This solved my issues


void LisaViewer::on_listImages_itemChanged(QListWidgetI tem* changed)
{
bool checked = changed->checkState() == Qt::Checked;
int index = 0;
for (; ui.listImages->item(index) != changed; index++) ;
QMessageBox::information(NULL,"Clicked", "You " + QString(checked ? "checked" : "unchecked") + " item " + QString::number(index + 1) + ".");
}

Lykurg
4th August 2010, 20:48
Instead of your for loop you can use QListWidget::row(const QListWidgetItem * item).