目录
1、Model/View结构对象和组件初始化
QStringListModel* theModel; QStringList theStrList ; theStrList<<"北京"<<"上海"<<"天津"<<"河北"<<"山东"<<"四川"<<"重庆"; theModel = new QStringListModel(this) ; theModel->setStringList (theStrList); //导入theStrList的内容 ui->listview->setModel(theModel) ; //设置数据模型 ui->listview->setEditTriggers(QAbstractItemview::Doubleclicked | QAbstractItemview::Selectedclicked) ;
setStringList()函数将一个字符串列表的内容作为数据模型的初始数据内容
setModel() : 为QListView设置一个数据模型
2、编辑、添加、删除操作
编辑项:
QListView:.setEditTriggers()函数设置QListView 的条目是否可以编辑,以及如何进入编辑状态,函数的参数是QAbstractIltemView::EditTrigger枚举类型值的组合。
//Doubleclicked 、Selectedclicked 在单击或者选择并单击列表后进入编辑状态 //NoEditTriggers 设置为不可编辑状态 ui->listview->setEditTriggers(QAbstractItemview::Doubleclicked | QAbstractItemview::Selectedclicked) ;
添加项:
//添加一行 //insertRow(int row) row 行号 在row之前插入一行,在列表的最后插入一行,参数设置为列表当前的行数 theModel->insertRow(theModel->rowCount());//在尾部插入一空行 //列表尾部添加一个空行 获得新增项的模型索引 QModelIndex index = theModel->index(theModel->rowCount () - 1, 0); //为新增项设置文字标题“new item” 在使用setData时必须指定设置数据的角色 theModel->setData(index, "new item", Qt::DisplayRole) ; ui->listview->setcurrentIndex (index) ; //设置当前选中的行
插入项:
/插入一行 QModelIndex index = ui->listview->currentIndex();//获取当前项的模型索引 theModel->insertRow (index.row());//index.row()返回模型索引的行号 theModel->setData (index, "inserted item", Qt::DisplayRole); ui->listview->setCurrentIndex (index) ;
删除当前项和列表:
/删除当前行 QModelIndex index = ui->listview->currentIndex (); theModel->removeRow(index.row()); //清除所有项 //QStringListModel 下的函数removeRows(int row, int count)从row开始删除count行 theModel->removeRows(0, theModel->rowCount()) ;