The QList
class is a template class that provides lists. It stores items in a list that provides fast index-based access and index-based insertions and removals.
To insert items into the list, you can use operator<<()
, insert()
, append()
or prepend()
. For example:
operator<<()
QList<QString> list;
list << "one" << "two" << "three";
insert()
QList<QString> list;
list << "alpha" << "beta" << "delta";
list.insert(2, "gamma");
append()
QList<QString> list;
list.append("one");
list.append("two");
list.append("three");
prepend()
QList<QString> list;
list.prepend("one");
list.prepend("two");
list.prepend("three");
To access the item at a particular index position, you can use operator[]()
or at()
. at()
may be faster than operator[]()
, it never causes deep copy of container and should work in constant-time. Neither of them does argument-check. Examples:
if (list[0] == "mystring")
cout << "mystring found" << endl;
Or
if (list.at(i) == "mystring")
cout << "mystring found at position " << i << endl;
To remove items, there are functions such as removeAt()
, takeAt()
, takeFirst()
, takeLast()
, removeFirst()
, removeLast()
, or removeOne()
. Examples:
takeFirst()
// takeFirst() removes the first item in the list and returns it
QList<QWidget *> list;
...
while (!list.isEmpty())
delete list.takeFirst();
removeOne()
// removeOne() removes the first occurrence of value in the list
QList<QString> list;
list << "sun" << "cloud" << "sun" << "rain";
list.removeOne("sun");
To find all occurrences of a particular value in a list, you can use indexOf()
or lastIndexOf()
. Example:
indexOf()
int i = list.indexOf("mystring");
if (i != -1)
cout << "First occurrence of mystring is at position " << i << endl;