A. Shears
A. Shears

Reputation: 115

Iterating through QList and calling functions on contained objects

I am having trouble iterating through my QList and calling the contained objects' member functions. I am trying to disable all push buttons in this window.

Here is my code

void TicTacToe::disableGame(){
    QList<QPushButton *> allPButtons = findChildren<QPushButton *>();
    QList<QPushButton *>::iterator i;
    for (i = allPButtons.begin(); i != allPButtons.end(); ++i)
        allPButtons[i]->setEnabled(false);
}

but it won't compile. So how to use iterator properly?

Upvotes: 3

Views: 3293

Answers (1)

David van rijn
David van rijn

Reputation: 2220

The point of an iterator is that you don't need the list (or other container object) anymore when iterating. You just need an iterator, that know how to walk through it's content, and an iterator that knows where it should stop.

the thing you have here is that you have an iterator of pointers, so you have to call operator*() on the iterator, and then * on your pointer ( or -> to make your life easier).

so you will need to use

(*i)->setEnabled(false);

You could also have a look at qt's foreach macro, or use a range based for loop. They make your code a lot cleaner and more clear.

Upvotes: 5

Related Questions