QList是目前最常用的容器类,它存储了给定类型的值的一个列表,而这些值可以通过索引访问。QList使用数组来实现,以确保进行快速的基于索引的访问。
使用QList::append和QList::prepend在列表的两端进行添加项目。
使用QList::insert()在列表的中间插入项目。
实例:
#include <QCoreApplication>
#include <QList>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QList<QString> list;
list << "aa" << "bb" << "cc"; // 插入项目
if(list[1] == "bb") list[1] = "ab";
list.replace(2, "bc"); // 将“cc”换为“bc”
qDebug() << "the list is: "; // 输出整个列表
for(int i=0; i<list.size(); ++i){
qDebug() << list.at(i); // 现在列表为aa ab bc
}
list.append("dd"); // 在列表尾部添加
list.prepend("mm"); // 在列表头部添加
QString str = list.takeAt(2); // 从列表中删除第3个项目,并获取它
qDebug() << "at(2) item is: "