开发者

Qt 4.6 - C++ - QTreeWidgetItem Iterator

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 开发者_StackOverflowtips? Thanks!


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜