Iterating through QTreeWidget Items

168 views Asked by At

I use a QTreeWidget in my project which is a list of tests that I want to run.

For example, Test 1, Test 2, Test 3, Test 4 etc.

Test 2 and Test 4 have children Test A, Test B, Test C etc.

Once Test 1 is done, I want Test A of Test 2 to be highlighted in the tree and display the correct form in my QVBoxLayout on the UI. Once Test A is finished running, I want Test 2 of Test B to be highlighted in the tree and showing the form.

enter image description here

I have tried the following:

In the .h file, I have:

QHash<int, QWidget*> treeFormHash;

The constructor in the .cpp file has this:

treeFormHash.insert(0,  Test1FormObj);
treeFormHash.insert(1,  Test2AFormObj);
treeFormHash.insert(2,  Test2BFormObj);
treeFormHash.insert(3,  Test3FormObj);
treeFormHash.insert(4,  Test4AFormObj);
treeFormHash.insert(5,  Test4BFormObj);

In the .cpp file:

void on_Next_btn_clicked() 
{ 
     QHashIterator<int, QWidget*> i(treeFormHash);

     QModelIndex currentTestStep = ui->treeWidget->currentIndex();

     int y = currentTestStep.row() + 1;

     currentTestStep = currentTestStep.siblingAtRow(y);

     QTreeWidgetItem *item = ui->treeWidget->currentItem();

     if(ui->treeWidget->itemBelow(item)->childCount() == 0)
     {
       ui->treeWidget->setCurrentItem(ui->treeWidget->itemBelow(item) , 0);
     }
     else
     {
       currentTestStep = currentTestStep.siblingAtRow(y+1);
       item = ui->treeWidget->currentItem();
       ui->treeWidget->setCurrentItem(ui->treeWidget->itemBelow(item) , 0);        
     }

     while(i.hasNext()) //Returns true if there is at least one item ahead of the iterator//
     {
        i.next();

        if(i.key() == y)
        {
           ui->verticalLayout->itemAt(0)->widget()->setVisible(false);
           ui->verticalLayout->insertWidget(0, i.value());
           break;
        }
    }
 } 
1

There are 1 answers

0
A.R.M On

The problem is that you're not realizing that if you need to iterate through a QTreeWidgetItem children, you have to consider that they are indexed relatively to their parent, meaning they are indexed from 0 to childrenCount()-1, not from parent->index()+1 to parent->index()+childrenCount().

Example:

- Test1 0

- Test2 1
     - TestA 0
     - TestB 1
     - TestC 2

 - Test3 2

 - Test4 3
     - TestA 0
     - TestB 1
     - TestC 2

Based on this, you can easily modify your code to handle iterating each item's children. And again, be careful to not iterate over childrenCount(), and to save the index of the iterated parent.