QStringListModel的使用
采用QStringListModel作为数据模型,QListView组件作为视图组件
演示了QStringListModel和QListView构成的Model/View结构编辑字符串列表的功能
窗口左侧是对QStringListView的一些操作,右侧的QPlainTextEdit组件显示QStringListModel::stringList()的内容,以查看其是否与QListView内容一致
widget.h文件
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QStringListModel>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
private slots:
void on_pushButton_2_clicked();
void on_pushButton_3_clicked();
void on_pushButton_4_clicked();
void on_pushButton_5_clicked();
void on_pushButton_clicked();
void on_pushButton_7_clicked();
void on_pushButton_6_clicked();
void on_listView_clicked(const QModelIndex &index);
private:
Ui::Widget *ui;
QStringListModel *theModel;//定义数据模型
};
#endif // WIDGET_H
widget.cpp文件
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
//进行变量的创建,完成数据模型与界面视图组件的关联
QStringList theStrList;
theStrList<<"北京"<<"南京"<<"西京"<<"东京";
theModel=new QStringListModel(this);
theModel->setStringList(theStrList);//导入theStrList的内容
ui->listView->setModel(theModel);//设置数据模型
ui->listView->setEditTriggers(QAbstractItemView::DoubleClicked|QAbstractItemView::SelectedClicked);//设置编辑模式
//双击或选中后单击进入编辑模式
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_pushButton_2_clicked()//添加项
{
theModel->insertRow(theModel->rowCount());//在最后一行之后再添加一行
QModelIndex index=theModel->index(theModel->rowCount()-1,0);//根据传递的行号、列号、父项的模型索引生成一个模型索引
theModel->setData(index,"new item",Qt::DisplayRole);//用于显示文字标题
ui->listView->setCurrentIndex(index);
}
void Widget::on_pushButton_3_clicked()//插入项
//在当前列表的前一行插入一行
{
QModelIndex index=ui->listView->currentIndex();//获取当前项的模型索引
theModel->insertRow(index.row());//将模型索引转化为行数
//在这一行前插入新行
theModel->setData(index,"insert item",Qt::DisplayRole);
ui->listView->setCurrentIndex(index);
}
void Widget::on_pushButton_4_clicked()//删除当前行
{
QModelIndex index=ui->listView->currentIndex();
theModel->removeRow(index.row());
}
void Widget::on_pushButton_5_clicked()//清除列表
{
theModel->removeRows(0,theModel->rowCount());
//参数1开始删除的行号
//参数2删除的行数
}
void Widget::on_pushButton_clicked()//恢复列表
{
QStringList theStrList;
theStrList<<"北京"<<"南京"<<"西京"<<"东京";
theModel=new QStringListModel(this);
theModel->setStringList(theStrList);//导入theStrList的内容
ui->listView->setModel(theModel);
}
void Widget::on_pushButton_7_clicked()//显示数据模型的StringList
{
QStringList tmpList;
tmpList=theModel->stringList();
ui->plainTextEdit->clear();
for(int i=0;i<tmpList.count();i++)
{
ui->plainTextEdit->appendPlainText(tmpList.at(i));
}
}
void Widget::on_pushButton_6_clicked()//清空文本
{
ui->plainTextEdit->clear();
}
void Widget::on_listView_clicked(const QModelIndex &index)//选择listView中的某项会显示行、列
{
int row=index.row();
int col=index.column();
ui->label->setText(QString::asprintf("当前项的行:%d,列:%d",row,col));
}