tags:

views:

190

answers:

3

Hello everyone! I have a QTreeWidget with items in it. The first column contains a unique number. This is set via item->setData(0, 0, unique_number);. The second column contains a checkbox, set via item->setCheckState(1, Qt::Unchecked);. The user can select the items (s)he would like to work with and presses a button. The slot for this button will run a loop on the checked items. In the Qt documentation an example is given. You use the QTreeWidgetItemIterator.

QTreeWidgetItemIterator it(treeWidget);
 while (*it) {
     if ((*it)->text(0) == itemText)
         (*it)->setSelected(true);
     ++it;
 }

It also says that you can specify an argument in the constructor to only iterate over the checked items. The flag is : QTreeWidgetItemIterator::Checked. My slightly customized loop is as follows:

QTreeWidgetItemIterator it(treeWidget, QTreeWidgetItemIterator::Checked);

while (*it)
{
    QVariant w;
    w = (*it)->data(0, 0);
    std::cout << "Selected item # " << w.toInt() << "\n";
    it++;

}

This code will compile fine but won't work when you actually run the program. It doesn't print any values.

Any tips? Thanks!

+1  A: 

The one caveat missing from the Qt documentation is that the QTreeWidgetItemIterator::Checked flag only tests the check state for column 0 in each of your QTreeWidgetItems. Using column 0 for your checkbox and column 1 for your unique number should cause the loop to print values.

RA
+1  A: 

Thanks Roneel!

Another way to do this is like this (I just figured it out).

QTreeWidgetItemIterator it(ui->treeWidget);

while (*it)
{

    if ((*it)->checkState(1) == 2)
    {
        QVariant w;
        w = (*it)->data(4, 0);
        std::cout << "Selected item # " << w.toString().toStdString() << "\n";
    }

    ++it;

}

checkState takes a int column argument and the == 2 only allows checked items to be processed.

Honza Pokorny
A: 

Just one thing... I think it's not a good habit to compare enum to int, as enum "int value" may change... Compare to Qt::Checked instead... It's just "for sure" and much more clean for reading

Kamil Klimek