How can I iterate over a foreach element in a QListWidget

I just can find any example on the Internet how to loop and get every element in a QListWidget

+6
c ++ qt
source share
2 answers
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()) { // A wild item has appeared } 
+9
source share

Google's first result for "QWidgetList" told me how to do this .

You can use the QWidgetListIt iterator.

 QWidgetList wl = get_some_widget_list(); for (QWidget* w = wl.first(); w != 0; w = wl.next()) { // use w } // or foreach (QWidget* w, wl) { // use w } 

I'm not quite sure where this foreach . If it is not provided by Qt, it could be a macro expanding to BOOST_FOREACH , for which you need to enable boost/foreach.hpp .

+1
source share

All Articles