C++ – how can iterate foreach item in QListWidget

c++qt

i just can find any example in the internet how to loop and get each item in the QListWidget

Best Solution

int count = listWidget->count();
for(int index = 0;
    index < count;
    index++)
{
    QListWidgetItem * item = listWidget->item(index);
    // A wild item has appeared
}

The foreach thing is totally different, I think.

If you want more info on that, look at this
http://doc.qt.digia.com/4.2/containers.html#the-foreach-keyword
scroll down to where it talks about the foreach keyword.


Special thanks to Tomalak Geret'kal for adding the proper characters which my keyboard is unable to produce :)


Due to so many upvotes on this, i'll explain the foreach macro here as well.

foreach is a Qt specific C++ addition, implemented using the preprocessor. If you want to disable the thing, just add CONFIG += no_keywords to your XX.pro file.

Qt makes a copy of the list being iterated, but don't worry about performance. Qt containers use implicit sharing, where the actual contents are not copied. Think of it as two reference variables using the same actual variable. This makes it possible to modify the list you are iterating over, without messing up the loop. Note that modifying the list forces Qt to make a copy of the actual contents of the list the first time it's modified.

foreach can be used to loop over all Qt basic containers, QList QVector QMap QMultiMap and so on. QListWidget is not one of these, so it doesn't work on it, sadly. To make matters worse, QListWidget doesn't provide a list of all items, only the ones selected. There is a method called items, which would seem to be nice, but is protected.

To loop over selected items, I think this would work

foreach(QListWidgetItem * item, listWidget->selectedItems())
{
    // A wild item has appeared
}