创建模型:
cpp
QStringListModel* model = new QStringListModel(this);
初始化列表:
cpp
QStringList strList;
strList << QStringLiteral("北京") << QStringLiteral("上海") << QStringLiteral("天津") << QStringLiteral("河北") << QStringLiteral("山东") << QStringLiteral("四川") << QStringLiteral("重庆") << QStringLiteral("广东") << QStringLiteral("河南");
将列表加进模型:
cpp
model->setStringList(strList);
为视图设置模型:
cpp
ui.listView->setModel(model);
添加行:
cpp
void port::on_addItem_clicked()
{
model->insertRow(model->rowCount());
QModelIndex index = model->index(model->rowCount() - 1,0);
model->setData(index,"new item",Qt::DisplayRole);
ui.listView->setCurrentIndex(index);
}
插入项:
cpp
void port::on_insertItem_clicked()
{
QModelIndex index;
index = ui.listView->currentIndex();
model->insertRow(index.row());
model->setData(index,"inserted item",Qt::DisplayRole);
model->setData(index,Qt::AlignRight,Qt::TextAlignmentRole);
ui.listView->setCurrentIndex(index);
}
删除项:
cpp
void port::on_deleteItem_clicked()
{
QModelIndex index;
index = ui.listView->currentIndex();
model->removeRow(index.row());
}
清空项:
cpp
void port::on_clearList_clicked()
{
model->removeRows(0,model->rowCount());
}
获取模型数据:
cpp
QStringList strList;
strList = model->stringList();
清空文本:
cpp
ui.plainTextEdit->clear();
将数据显示到文本上:
cpp
for (int i = 0; i < strList.count(); i++)
ui.plainTextEdit->appendPlainText(strList.at(i));