QStringListModel是最简单的模型类,具备向视图提供字符串数据的能力。QStringListModel是一个可编辑的模型,可以为组件提供一系列字符串作为数据。
下面我们通过一个例子来看看QStringListModel的使用。首先是我们的构造函数:
-
MyListView::MyListView()
-
{
-
QStringList data;
-
data << "Letter A" << "Letter B" << "Letter C";
-
model = new QStringListModel(this);
-
model->setStringList(data);
-
-
listView = new QListView(this);
-
listView->setModel(model);
-
-
QHBoxLayout *btnLayout = new QHBoxLayout;
-
QPushButton *insertBtn = new QPushButton(tr("insert"), this);
-
connect(insertBtn, SIGNAL(clicked()), this, SLOT(insertData()));
-
QPushButton *delBtn = new QPushButton(tr("Delete"), this);
-
connect(delBtn, SIGNAL(clicked()), this, SLOT(deleteData()));
-
-
btnLayout->addWidget(insertBtn);
-
btnLayout->addWidget(delBtn);
-
-
QVBoxLayout *mainLayout = new QVBoxLayout(this);
-
mainLayout->addWidget(listView);
-
mainLayout->addLayout(btnLayout);
-
setLayout(mainLayout);
-
}
接下来我们来看几个按钮的响应槽函数。
-
void MyListView::insertData()
-
{
-
bool isOK;
-
QString text = QInputDialog::getText(this, "Insert",
-
"Please input new data:",
-
QLineEdit::Normal,
-
"You are inserting new data.",
-
&isOK); //要求用户输入数据
-
if (isOK) {
-
QModelIndex currIndex = listView->currentIndex();
-
model->insertRows(currIndex.row(), 1);
-
model->setData(currIndex, text);
-
listView->edit(currIndex);//使这一行可以被编辑
-
}
接下来是删除数据:
void MyListView::deleteData()
{
if (model->rowCount() > 1) {
model->removeRows(listView->currentIndex().row(), 1);
}
}
阅读(2659) | 评论(0) | 转发(1) |