QStringListModel


关于这个类

QStringListModel 用于处理字符串列表的数据模型,配对的显示组件是 QListView,它的数据结构是 QStringList,初始化函数为 setStringList(),取值函数是 stringList()

下面的小程序,演示其用法。

代码

  • mywidget.cpp
#include "mywidget.h"
#include "./ui_mywidget.h"

myWidget::myWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::myWidget)
{
    ui->setupUi(this);
    QStringList theStringList;
    theStringList <<"北京"<<"上海"<<"天津"<<"武汉"<<"郑州"<<"新乡"<<"海南";
    theModelList = new QStringListModel(this);
    theModelList->setStringList(theStringList);
    ui->listView->setModel(theModelList);
    ui->listView->setEditTriggers(QAbstractItemView::DoubleClicked|QAbstractItemView::SelectedClicked);
}

myWidget::~myWidget()
{
    delete ui;
}



void myWidget::on_btnAddList_clicked()
{
    theModelList->insertRow(theModelList->rowCount());
    QModelIndex index = theModelList->index(theModelList->rowCount()-1);
    theModelList->setData(index,"new item",Qt::DisplayRole);
    ui->listView->setCurrentIndex(index);
}


void myWidget::on_btnInsert_clicked()
{
    QModelIndex index = ui->listView->currentIndex();
    theModelList->insertRow(index.row());
    theModelList->setData(index,"new inserted item",Qt::DisplayRole);
    ui->listView->setCurrentIndex(index);
}


void myWidget::on_btnDelItem_clicked()
{
    QModelIndex index = ui->listView->currentIndex();
    theModelList->removeRow(index.row());
}



void myWidget::on_btnCleanList_clicked()
{
    theModelList->removeRows(0,theModelList->rowCount());
}


void myWidget::on_btnReList_clicked()
{
    QStringList theStringList;
    theStringList <<"北京"<<"上海"<<"天津"<<"武汉"<<"郑州"<<"新乡"<<"海南";
    theModelList->setStringList(theStringList);
}


void myWidget::on_btnDisplayListView_clicked()
{
    QStringList tmpList=theModelList->stringList();
    ui->plainTextEdit->clear();
    for(int i=0;i<tmpList.count();i++)
        ui->plainTextEdit->appendPlainText(tmpList.at(i));
}



void myWidget::on_btnCleanText_clicked()
{
    ui->plainTextEdit->clear();
}


void myWidget::on_listView_clicked(const QModelIndex &index)
{
    ui->labelInfo->setText(QString::asprintf("当前条目:row=%d,column=%d",index.row(),index.column()));
}

  • mywidget.h
#ifndef MYWIDGET_H
#define MYWIDGET_H

#include <QWidget>
#include <QStringListModel>
#include <QStringList>

QT_BEGIN_NAMESPACE
namespace Ui { class myWidget; }
QT_END_NAMESPACE

class myWidget : public QWidget
{
    Q_OBJECT

public:
    myWidget(QWidget *parent = nullptr);
    ~myWidget();

private slots:
    void on_btnAddList_clicked();

    void on_btnInsert_clicked();

    void on_btnDelItem_clicked();

    void on_btnCleanList_clicked();

    void on_btnReList_clicked();

    void on_btnDisplayListView_clicked();

    void on_btnCleanText_clicked();

    void on_listView_clicked(const QModelIndex &index);

private:
    QStringListModel *theModelList;
    Ui::myWidget *ui;
};
#endif // MYWIDGET_H

运行结果

sample52.png


文章作者: 五笔小筑
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 五笔小筑 !
评论