Qt5 Tutorial QMutableListIterator - 2020
In this tutorial, we will learn about QMutableListIterator.
The QMutableListIterator class provides a Java-style non-const iterator for QList.
QMutableListIterator<T> allows us to iterate over a QList<<T>> and modify the list. If we don't want to modify the list (or have a const QList), use the slightly faster QListIterator<T> instead.
#include <QCoreApplication> #include <QList> #include <QDebug> #include <QListIterator> #include <QMutableListIterator> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QList<int> List; for(int i = 0; i < 10; i++) List.append(i); // The QMutableListIterator constructor takes a QList // as argument. After construction, the iterator // is located at the very beginning of the list // (before the first item) QMutableListIterator<int> mIter(List); qDebug() << "Modifying element while moving forward..."; while(mIter.hasNext()) { // The next() function returns the next item // in the list and advances the iterator. // To remove items as we iterate over the list, // we use remove(). // To modify the value of an item, // we use setValue(). int val = mIter.next(); // odd: remove, even: negate if (val % 2 == 1) mIter.remove(); else if (val % 2 == 0) mIter.setValue(-val); } qDebug() << "Start again from front..."; // toFront() voves the iterator to the front // of the container (before the first item). mIter.toFront(); qDebug() << "Forward..."; while(mIter.hasNext()) qDebug() << mIter.next(); return a.exec(); }
Output:
Modifying element while moving forward... Start again from front... Forward... 0 -2 -4 -6 -8
Note that the QMutableListIterator constructor takes a QList as argument. After construction, the iterator is located at the very beginning of the list (before the first item).
We used remove() to remove items as we iterate over the list. To modify the value of an item, we used setValue().
The toFront() moves the iterator to the front of the container (before the first item).
Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization