int count = listWidget->count(); for(int index = 0; index < count; index++) { QListWidgetItem * item = listWidget->item(index); // A wild item has appeared }
foreach thing is completely different, I think.
If you want more information about this, look at this.
http://doc.qt.digia.com/4.2/containers.html#the-foreach-keyword
scroll down to where the foreach keyword is mentioned.
Special thanks to Tomalak Geret'kal for adding the correct characters that my keyboard cannot produce :)
Due to the large number of upvotes on this, I will also explain the foreach macro.
foreach is a special complement to C ++ defined using a preprocessor. If you want to disable this thing, just add CONFIG + = no_keywords to your XX.pro file.
Qt copies the list, repeating, but don't worry about performance. Qt containers use implicit sharing when the actual content is not copied. Think of it as two control variables using the same actual variable. This allows you to change the list that you repeat without messing up the loop. Note that changing the list causes Qt to copy the actual contents of the list on the first change.
foreach can be used to process all the underlying Qt containers, QList QVector QMap QMultiMap, etc. QListWidget is not one of them, so unfortunately this does not work. Worse, QListWidget does not provide a list of all the items just selected. There is a method called elements that will seem enjoyable, but protected.
To iterate over the selected items, I think it will work
foreach(QListWidgetItem * item, listWidget->selectedItems()) {
0xbaadf00d
source share