How to iterate QList ?
-
I am not too comfortable using "foreach" ...... however, is there something very basic wrong with my code ?
Or am I missing more ?
define foreach Q_FOREACH
QList<QObject*> pLIST = this->children(); QObject item; //#ifdef BYPASS foreach(auto &pLIST, item ) { text = " Iterate ............. "; qDebug().noquote() << text; }
One of the errors posted
/home/nov25-1/Qt/5.15.2/gcc_64/include/QtCore/qglobal.h:1085: error: no type named 'const_iterator' in 'QObject' In file included from settingsdialog.cpp:55: In file included from ./mainwindow_Bluetooth.h:61: In file included from ../CCC_SOURCE/A_BT_TEST_A/../dialog_connection.h:4: In file included from /home/nov25-1/Qt/5.15.2/gcc_64/include/QtWidgets/QDialog:1: In file included from /home/nov25-1/Qt/5.15.2/gcc_64/include/QtWidgets/qdialog.h:43: In file included from /home/nov25-1/Qt/5.15.2/gcc_64/include/QtWidgets/qtwidgetsglobal.h:43: In file included from /home/nov25-1/Qt/5.15.2/gcc_64/include/QtGui/qtguiglobal.h:43: /home/nov25-1/Qt/5.15.2/gcc_64/include/QtCore/qglobal.h:1085:17: error: no type named 'const_iterator' in 'QObject' typename T::const_iterator i, e; ~~~~~~~~~~~~^~~~~~~~~~~~~~ settingsdialog.cpp:1241:5: note: in instantiation of template class 'QtPrivate::QForeachContainer<QObject>' requested here foreach(auto &pLIST, item ) ^ /home/nov25-1/Qt/5.15.2/gcc_64/include/QtCore/qglobal.h:1126:21: note: expanded from macro 'foreach' # define foreach Q_FOREACH ^ /home/nov25-1/Qt/5.15.2/gcc_64/include/QtCore/qglobal.h:1115:25: note: expanded from macro 'Q_FOREACH' for (auto _container_ = QtPrivate::qMakeForeachContainer(container); \ ^
-
foreach(auto &pLIST, item )
item is not a QList
-
@AnneRanch said in How to iterate QList ?:
foreach(auto &pLIST, item ) { text = " Iterate ............. "; qDebug().noquote() << text; }
for( auto const list_item : pLIST ) { text = " Iterate ............. "; qDebug().noquote() << text; }
-
Thank you, I am not sure why I cannot get the parameters in correct order...
Mental block, I guss.One more question :
how important is to designate the item as "const" ? -
@AnneRanch my own habit. If list_item is not changed in the loop, you can add a const to enforce it. If anything of list_item is changed by accident, the compiler will tell it is wrong. But maybe no big deal in your app. Up to you.
-
I would recommend to no longer use Q_FOREACH it is deprecated for a reason! Use the ranged based for loop the c++ standard offers
for (auto &item : container)
less error prone, less conflict with other libraries, faster compile times.
-