QStandardItemModel

Posted samp000

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了QStandardItemModel相关的知识,希望对你有一定的参考价值。

最近在阅读Qt 5.9 C++开发指南,为了加深对书本上内容的理解,参照书上的讲解尝试写了一些demo,用于以后工作中查阅,如果涉及侵权请告知实例程序samp5_3

mainwindow.h

 

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QTableView>
#include <QPlainTextEdit>
#include <QLabel>
#include <QAction>
#include <QStandardItemModel>
#include <QItemSelectionModel>

#define FixedColumnCount 6

class MainWindow : public QMainWindow
{
    Q_OBJECT

private:
    QAction *_actionOpenFile;
    QAction *_actionSaveFile;
    QAction *_actionModelDataPreview;
    QAction *_actionAddLine;
    QAction *_actionInsertLine;
    QAction *_actionDeleteLine;
    QAction *_actionLeft;
    QAction *_actionCenter;
    QAction *_actionRight;
    QAction *_actionBold;
    QAction *_actionExit;
    QTableView *_tableView;
    QPlainTextEdit *_plainTextEdit;
    QLabel *_labelCurrentFile;
    QLabel *_labelCurrentPos;
    QLabel *_labelCurrentContent;

    QStandardItemModel *_standardItemModel;
    QItemSelectionModel *_itemSelectionModel;

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();
    void iniUI();
    void iniSignalSlots();
    void iniModel(QStringList &stringList);

public slots:
    void onCurrentChanged(QModelIndex current, QModelIndex previous);
    void triggeredActionOpenFile();
    void triggeredActionSaveFile();
    void triggeredActionModelDataPreview();
    void triggeredActionAddLine();
    void triggeredActionInsertLine();
    void triggeredActionDeleteLine();
    void triggeredActionLeft();
    void triggeredActionCenter();
    void triggeredActionRight();
    void triggeredActionBold();
    void triggeredActionExit();

};

#endif // MAINWINDOW_H

 

 

 

mainwind.cpp

 

#include <QIcon>
#include <QToolBar>
#include <QSplitter>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QGroupBox>
#include <QStatusBar>
#include <QCoreApplication>
#include <QDir>
#include <QFileDialog>
#include <QFile>
#include <QTextStream>
#include <QStringList>
#include <QRegExp>
#include <QStandardItem>
#include <QList>
#include <QModelIndex>
#include <QModelIndexList>

#include "mainwindow.h"

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{
    iniUI();
    iniSignalSlots();

    _standardItemModel = new QStandardItemModel(2, FixedColumnCount, this);
    _itemSelectionModel = new QItemSelectionModel(_standardItemModel);
    connect(_itemSelectionModel, SIGNAL(currentChanged(QModelIndex, QModelIndex)), this, SLOT(onCurrentChanged(QModelIndex, QModelIndex)));

    _tableView->setModel(_standardItemModel);
    _tableView->setSelectionModel(_itemSelectionModel);
    _tableView->setSelectionMode(QAbstractItemView::ExtendedSelection);
    _tableView->setSelectionBehavior(QAbstractItemView::SelectItems);
}

MainWindow::~MainWindow()
{

}

void MainWindow::iniUI()
{
    _actionOpenFile = new QAction(QIcon(":/images/open.bmp"), "打开文件");
    _actionSaveFile = new QAction(QIcon(":/images/save.bmp"), "另存文件");
    _actionModelDataPreview = new QAction(QIcon(":/images/import1.bmp"), "模型数据预览");
    _actionAddLine = new QAction(QIcon(":/images/append.bmp"), "添加行");
    _actionInsertLine = new QAction(QIcon(":/images/insert.bmp"), "插入行");
    _actionDeleteLine = new QAction(QIcon(":/images/remove.bmp"), "删除行");
    _actionLeft = new QAction(QIcon(":/images/508.bmp"), "居左");
    _actionCenter = new QAction(QIcon(":/images/510.bmp"), "居中");
    _actionRight = new QAction(QIcon(":/images/512.bmp"), "居右");
    _actionBold = new QAction(QIcon(":/images/500.bmp"), "粗体");
    _actionExit = new QAction(QIcon(":/images/exit.bmp"), "退出");

    QToolBar *toolBar = new QToolBar();
    toolBar->addAction(_actionOpenFile);
    toolBar->addAction(_actionSaveFile);
    toolBar->addAction(_actionModelDataPreview);
    toolBar->addSeparator();
    toolBar->addAction(_actionAddLine);
    toolBar->addAction(_actionInsertLine);
    toolBar->addAction(_actionDeleteLine);
    toolBar->addSeparator();
    toolBar->addAction(_actionLeft);
    toolBar->addAction(_actionCenter);
    toolBar->addAction(_actionRight);
    toolBar->addAction(_actionBold);
    toolBar->addSeparator();
    toolBar->addAction(_actionExit);
    toolBar->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);

    _tableView = new QTableView();
    QVBoxLayout *layout1 = new QVBoxLayout();
    layout1->addWidget(_tableView);
    QGroupBox *groupBox1 = new QGroupBox("TableView");
    groupBox1->setLayout(layout1);

    _plainTextEdit = new QPlainTextEdit();
    QVBoxLayout *layout2 = new QVBoxLayout();
    layout2->addWidget(_plainTextEdit);
    QGroupBox *groupBox2 = new QGroupBox("PlainTextEdit");
    groupBox2->setLayout(layout2);

//    QSplitter *splitter = new QSplitter();

    QHBoxLayout *layout3 = new QHBoxLayout();
    layout3->addWidget(groupBox1);
//    layout3->addWidget(splitter);
    layout3->addWidget(groupBox2);

    QWidget *widget = new QWidget();
    widget->setLayout(layout3);

    _labelCurrentFile = new QLabel();
    _labelCurrentPos = new QLabel();
    _labelCurrentContent = new QLabel();

    QStatusBar *statusBar = new QStatusBar();
    statusBar->addWidget(_labelCurrentFile);
    statusBar->addWidget(_labelCurrentPos);
    statusBar->addWidget(_labelCurrentContent);

    setStatusBar(statusBar);
    setCentralWidget(widget);
    addToolBar(toolBar);
    resize(800, 600);
}

void MainWindow::iniSignalSlots()
{
    connect(_actionOpenFile, SIGNAL(triggered()), this, SLOT(triggeredActionOpenFile()));
    connect(_actionSaveFile, SIGNAL(triggered()), this, SLOT(triggeredActionSaveFile()));
    connect(_actionModelDataPreview, SIGNAL(triggered()), this, SLOT(triggeredActionModelDataPreview()));
    connect(_actionAddLine, SIGNAL(triggered()), this, SLOT(triggeredActionAddLine()));
    connect(_actionInsertLine, SIGNAL(triggered()), this, SLOT(triggeredActionInsertLine()));
    connect(_actionDeleteLine, SIGNAL(triggered()), this, SLOT(triggeredActionDeleteLine()));
    connect(_actionLeft, SIGNAL(triggered()), this, SLOT(triggeredActionLeft()));
    connect(_actionCenter, SIGNAL(triggered()), this, SLOT(triggeredActionCenter()));
    connect(_actionRight, SIGNAL(triggered()), this, SLOT(triggeredActionRight()));
    connect(_actionBold, SIGNAL(triggered()), this, SLOT(triggeredActionBold()));
    connect(_actionExit, SIGNAL(triggered()), this, SLOT(triggeredActionExit()));
}

void MainWindow::triggeredActionOpenFile()
{
    QString caption = "打开一个文件";
    QString dir = QDir::currentPath();
    QString filter = "井数据文件(*.txt);;所有文件(*.*)";
    QString fileName = QFileDialog::getOpenFileName(this, caption, dir, filter);

    if(fileName.isEmpty())
    {
        return;
    }

    QStringList stringList;
    QFile file(fileName);
    if(file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        QTextStream stream(&file);
        while(!stream.atEnd())
        {
            QString text = stream.readLine();
            stringList.append(text);
        }
    }
    file.close();

    _labelCurrentFile->setText(fileName);
    iniModel(stringList);
}

void MainWindow::triggeredActionSaveFile()
{
    QString caption = "选择一个文件";
    QString dir = QDir::currentPath();
    QString filter = "井数据文件(*.txt);;所有文件(*.*)";
    QString fileName = QFileDialog::getOpenFileName(this, caption, dir, filter);

    if(fileName.isEmpty())
    {
        return;
    }

    QFile file(fileName);
    if(file.open(QIODevice::WriteOnly | QIODevice::Text))
    {
        QTextStream stream(&file);
        QStandardItem *item;
        QString text;

        for(int i = 0; i < _standardItemModel->columnCount(); i++)
        {
            item = _standardItemModel->horizontalHeaderItem(i);
            text = text + item->text() + "		";
        }
        stream << text << "
";

        for(int i = 0; i < _standardItemModel->rowCount(); i++)
        {
            text.clear();
            for(int j = 0; j < _standardItemModel->columnCount() - 1; j++)
            {
                item = _standardItemModel->item(i, j);
                text = text + item->text() + "		";
            }

            item = _standardItemModel->item(i, _standardItemModel->columnCount() - 1);
            int checkState = item->checkState();
            if(checkState == 0)
            {
                text = text + "0		";
            }
            else
            {
                text = text + "1		";
            }
            stream << text << "
";
        }
    }
    file.close();
}

void MainWindow::triggeredActionModelDataPreview()
{
    _plainTextEdit->clear();

    QStandardItem *item;
    QString text;

    for(int i = 0; i < _standardItemModel->columnCount(); i++)
    {
        item = _standardItemModel->horizontalHeaderItem(i);
        text = text + item->text() + "		";
    }
    _plainTextEdit->appendPlainText(text);

    for(int i = 0; i < _standardItemModel->rowCount(); i++)
    {
        text.clear();
        for(int j = 0; j < _standardItemModel->columnCount() - 1; j++)
        {
            item = _standardItemModel->item(i, j);
            text = text + item->text() + "		";
        }

        item = _standardItemModel->item(i, _standardItemModel->columnCount() - 1);
        int checkState = item->checkState();
        if(checkState == 0)
        {
            text = text + "0		";
        }
        else
        {
            text = text + "1		";
        }
        _plainTextEdit->appendPlainText(text);
    }
}

void MainWindow::iniModel(QStringList &stringList)
{
    int count = stringList.count();
    _standardItemModel->setRowCount(count - 1);

    QString header = stringList.at(0);
    QStringList headerList = header.split(QRegExp("\s+"), QString::SkipEmptyParts);
    _standardItemModel->setHorizontalHeaderLabels(headerList);

    QStandardItem *standardItem;
    QStringList tempList;
    int j = 0;
    for(int i = 1; i < stringList.size(); i++)
    {
        QString text = stringList.at(i);
        tempList = text.split(QRegExp("\s+"), QString::SkipEmptyParts);
        for(j = 0; j < tempList.size() - 1; j++)
        {
            standardItem = new QStandardItem(tempList.at(j));
            _standardItemModel->setItem(i - 1, j, standardItem);
        }

        standardItem = new QStandardItem(headerList.at(j));
        standardItem->setCheckable(true);
        if(tempList.at(j) == "1")
        {
            standardItem->setCheckState(Qt::Checked);
        }
        else
        {
            standardItem->setCheckState(Qt::Unchecked);
        }
        _standardItemModel->setItem(i - 1, j, standardItem);
    }
}

void MainWindow::triggeredActionAddLine()
{
    QList<QStandardItem *> itemList;
    QStandardItem *item;
    for(int i = 0; i < _standardItemModel->columnCount() - 1; i++)
    {
        item = new QStandardItem("");
        itemList.append(item);
    }

    QString headData = _standardItemModel->headerData(_standardItemModel->columnCount() - 1, Qt::Horizontal, Qt::DisplayRole).toString();
    item = new QStandardItem(headData);
    item->setCheckable(true);
    itemList.append(item);

    _standardItemModel->insertRow(_standardItemModel->rowCount(), itemList);
    QModelIndex index = _standardItemModel->index(_standardItemModel->rowCount() - 1, 0);

    _itemSelectionModel->clearSelection();
    _itemSelectionModel->setCurrentIndex(index, QItemSelectionModel::Select);
}

void MainWindow::triggeredActionInsertLine()
{
    QList<QStandardItem *> itemList;
    QStandardItem *item;
    for(int i = 0; i < FixedColumnCount - 1; i++)
    {
        item = new QStandardItem("");
        itemList.append(item);
    }

    QString headData = _standardItemModel->headerData(_standardItemModel->columnCount() - 1, Qt::Horizontal, Qt::DisplayRole).toString();
    item = new QStandardItem(headData);
    item->setCheckable(true);
    itemList.append(item);

    QModelIndex index = _tableView->currentIndex();
    _standardItemModel->insertRow(index.row(), itemList);

//    _standardItemModel->insertRow(_standardItemModel->rowCount(), itemList);
//    QModelIndex index = _standardItemModel->index(_standardItemModel->rowCount() - 1, 0);

    _itemSelectionModel->clearSelection();
    _itemSelectionModel->setCurrentIndex(index, QItemSelectionModel::Select);
}

void MainWindow::triggeredActionDeleteLine()
{
    QModelIndex index = _tableView->currentIndex();
    _standardItemModel->removeRow(index.row());
}

void MainWindow::triggeredActionLeft()
{
    if(!_itemSelectionModel->hasSelection())
    {
        return;
    }

    QModelIndexList indexList = _itemSelectionModel->selectedIndexes();
    for(int i = 0; i < indexList.count(); i++)
    {
        QModelIndex index = indexList.at(i);
        QStandardItem *item = _standardItemModel->itemFromIndex(index);
        item->setTextAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    }
}

void MainWindow::triggeredActionCenter()
{
    if(!_itemSelectionModel->hasSelection())
    {
        return;
    }

    QModelIndexList indexList = _itemSelectionModel->selectedIndexes();
    for(int i = 0; i < indexList.count(); i++)
    {
        QModelIndex index = indexList.at(i);
        QStandardItem *item = _standardItemModel->itemFromIndex(index);
        item->setTextAlignment(Qt::AlignHCenter| Qt::AlignVCenter);
    }
}

void MainWindow::triggeredActionRight()
{
    if(!_itemSelectionModel->hasSelection())
    {
        return;
    }

    QModelIndexList indexList = _itemSelectionModel->selectedIndexes();
    for(int i = 0; i < indexList.count(); i++)
    {
        QModelIndex index = indexList.at(i);
        QStandardItem *item = _standardItemModel->itemFromIndex(index);
        item->setTextAlignment(Qt::AlignRight| Qt::AlignVCenter);
    }
}

void MainWindow::triggeredActionBold()
{
    if(!_itemSelectionModel->hasSelection())
    {
        return;
    }

    QModelIndexList indexList = _itemSelectionModel->selectedIndexes();
    for(int i = 0; i < indexList.count(); i++)
    {
        QModelIndex index = indexList.at(i);
        QStandardItem *item = _standardItemModel->itemFromIndex(index);
        QFont font = item->font();
        if(font.bold())
        {
            font.setBold(false);
        }
        else
        {
            font.setBold(true);
        }
        item->setFont(font);
    }
}

void MainWindow::triggeredActionExit()
{
    close();
}


void MainWindow::onCurrentChanged(QModelIndex current, QModelIndex previous)
{
    if(!current.isValid())
    {
        return;
    }

    _labelCurrentPos->setText(QString::asprintf("		当前单元格:%d行,%d列", current.row() + 1, current.column() + 1));

    QStandardItem *item = _standardItemModel->itemFromIndex(current);
    _labelCurrentContent->setText("		单元格内容:" + item->text());
}

 

 

 

main.cpp

 

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

 

以上是关于QStandardItemModel的主要内容,如果未能解决你的问题,请参考以下文章

如何与复选框操作进行交互? (带有 QStandardItemModel 的 QTableView)

将 QStandardItemModel 从 C++ 传递到 QtQuick / QML TableView 并显示它

QT QTableView(基于QStandardItemModel用法)操作详解

QT QTableView(基于QStandardItemModel用法)操作详解

QT QTableView(基于QStandardItemModel用法)操作详解

如何复制 - 将 QStandardItemModel 创建的 QTableView 中的多个项目粘贴到文本/excel 文件中?