QStringListModel

2760阅读 0评论2013-12-23 luozhiyong131
分类:嵌入式

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

    }

}



上一篇:Qt简单模型
下一篇:Qt使用拖放