Chinaunix首页 | 论坛 | 博客
  • 博客访问: 7566105
  • 博文数量: 961
  • 博客积分: 15795
  • 博客等级: 上将
  • 技术积分: 16612
  • 用 户 组: 普通用户
  • 注册时间: 2010-08-07 14:23
文章分类

全部博文(961)

文章存档

2016年(1)

2015年(61)

2014年(41)

2013年(51)

2012年(235)

2011年(391)

2010年(181)

分类: 嵌入式

2013-12-23 11:38:00

QStringListModel是最简单的模型类,具备向视图提供字符串数据的能力。QStringListModel是一个可编辑的模型,可以为组件提供一系列字符串作为数据。
 

下面我们通过一个例子来看看QStringListModel的使用。首先是我们的构造函数:

点击(此处)折叠或打开

  1. MyListView::MyListView()
  2. {
  3.     QStringList data;
  4.     data << "Letter A" << "Letter B" << "Letter C";
  5.     model = new QStringListModel(this);
  6.     model->setStringList(data);

  7.     listView = new QListView(this);
  8.     listView->setModel(model);

  9.     QHBoxLayout *btnLayout = new QHBoxLayout;
  10.     QPushButton *insertBtn = new QPushButton(tr("insert"), this);
  11.     connect(insertBtn, SIGNAL(clicked()), this, SLOT(insertData()));
  12.     QPushButton *delBtn = new QPushButton(tr("Delete"), this);
  13.     connect(delBtn, SIGNAL(clicked()), this, SLOT(deleteData()));
  14.     
  15.     btnLayout->addWidget(insertBtn);
  16.     btnLayout->addWidget(delBtn);

  17.     QVBoxLayout *mainLayout = new QVBoxLayout(this);
  18.     mainLayout->addWidget(listView);
  19.     mainLayout->addLayout(btnLayout);
  20.     setLayout(mainLayout);
  21. }

接下来我们来看几个按钮的响应槽函数。


点击(此处)折叠或打开

  1. void MyListView::insertData()
  2. {
  3.     bool isOK;
  4.     QString text = QInputDialog::getText(this, "Insert",
  5.                                          "Please input new data:",
  6.                                          QLineEdit::Normal,
  7.                                          "You are inserting new data.",
  8.                                          &isOK); //要求用户输入数据
  9.     if (isOK) {
  10.        QModelIndex currIndex = listView->currentIndex();
  11.         model->insertRows(currIndex.row(), 1);
  12.         model->setData(currIndex, text);
  13.         listView->edit(currIndex);//使这一行可以被编辑
  14. }

接下来是删除数据:

void MyListView::deleteData()

{

    if (model->rowCount() > 1) {

        model->removeRows(listView->currentIndex().row(), 1);

    }

}



阅读(2615) | 评论(0) | 转发(1) |
0

上一篇:Qt简单模型

下一篇:Qt使用拖放

给主人留下些什么吧!~~