qt -- QStringListModel的使用

目录

1、Model/View结构对象和组件初始化  

2、编辑、添加、删除操作


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()) ;

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值