QT5笔记: 21. QStandardItemModel

QStandardItemModel 存放数据

QItemSelectionModel 选择项模型

例子:本例子中QListView 没有做任何处理,只是拖放至ui文件,设置了布局

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QItemSelectionModel>
#include <QLabel>
#include <QMainWindow>
#include <QStandardItemModel>

#define COL 6 //行数

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

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

private slots:
    void on_currentChanged(const QModelIndex &current, const QModelIndex &previous);
    void on_actOpen_triggered();

    void on_actSave_triggered();

    void on_actAppend_triggered();

    void on_actInsert_triggered();

    void on_actDelete_triggered();

    void on_actAlignLeft_triggered();

    void on_actAlignCenter_triggered();

    void on_actAlignRight_triggered();

    void on_actFontBold_triggered(bool checked);

private:
    Ui::MainWindow *ui;

    QLabel *labelPath;//路径信息
    QLabel *labelCellPos;//单元格行列号
    QLabel *labelCellText;//单元格信息

    QStandardItemModel *model;//数据model
    QItemSelectionModel *selectModel;//选择model

    void initItemModel(QStringList list);//文本为model填充数据

    void setTextAlign(Qt::Alignment atextAlignment);//设置文本对齐方式
};
#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QAbstractItemView>
#include <QFileDialog>
#include <QFileDialog>
#include <QTextStream>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    labelPath = new QLabel("当前文件:", this);
    labelPath->setMinimumWidth(225);
    labelCellPos = new QLabel("当前位置:", this);
    labelCellPos->setMinimumWidth(75);
    labelCellText = new QLabel("当前内容:", this);
    labelCellText->setMinimumWidth(150);
    ui->statusbar->addWidget(labelPath);
    ui->statusbar->addWidget(labelCellPos);
    ui->statusbar->addWidget(labelCellText);

    model = new QStandardItemModel(10, COL,  this);
    selectModel = new QItemSelectionModel(model);
    ui->tableView->setModel(model);//设置模型
    ui->tableView->setSelectionModel(selectModel);//选择模型
    ui->tableView->setSelectionMode(QAbstractItemView::ExtendedSelection);
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectItems);

    connect(selectModel, SIGNAL(currentChanged(QModelIndex, QModelIndex)), this, SLOT(on_currentChanged(QModelIndex, QModelIndex)));
}

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

void MainWindow::on_currentChanged(const QModelIndex &current, const QModelIndex &previous)
{
    Q_UNUSED(previous);
    if (!current.isValid()) {
        return;
    }
    labelCellPos->setText(QString("第 %1 行,第 %2 列").arg(current.row()).arg(current.column()));
    QStandardItem *item = model->itemFromIndex(current);//根据index获取到item
    labelCellText->setText("当前单元格内容:" + item->text());
    QFont font = item->font();
    ui->actFontBold->setChecked(font.bold());
}


void MainWindow::on_actOpen_triggered()//打开文件,并将文件数据加载进数据模型
{
    QString curPath = QCoreApplication::applicationDirPath();
    QString name = QFileDialog::getOpenFileName(this, "打开文件", curPath, "文本文件(*.txt);;所有文件(*.*)");
    if (name.isEmpty()) {
        return;
    }
    QStringList list;//文本内容

    QFile file(name);
    if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        ui->plainTextEdit->clear();
        QTextStream stream(&file);
        while (!stream.atEnd()) {
            QString lineText = stream.readLine();
            ui->plainTextEdit->appendPlainText(lineText);
            list.append(lineText);
        }
        this->labelPath->setText("当前文件:" + curPath);

        initItemModel(list);
        ui->tableView->resizeRowsToContents();
        ui->tableView->resizeColumnsToContents();

        ui->actSave->setEnabled(true);
        ui->actInsert->setEnabled(true);
        ui->actAppend->setEnabled(true);
        ui->actDelete->setEnabled(true);
    }
}

/**
 * @brief MainWindow::initItemModel 根据文本文件为Model填充数据
 * @param list
 */
void MainWindow::initItemModel(QStringList list)
{
    model->setRowCount(list.size() - 1);
    QString header = list.at(0);
    QStringList headerList = header.split(QRegExp("\\s+"), QString::SkipEmptyParts);
    model->setHorizontalHeaderLabels(headerList);//设置表头

    for (int i = 1; i < list.count(); i++) {
        int j = 0;
        QStringList contents = list.at(i).split(QRegExp("\\s+"), QString::SkipEmptyParts);
        for (; j < COL - 1; j++) {
            QStandardItem *item = new QStandardItem(contents.at(j));
            model->setItem(i - 1, j, item);
        }
        QStandardItem *checkItem = new QStandardItem();
        checkItem->setCheckState(contents.at(j) == "1" ? Qt::Checked : Qt::Unchecked);
        model->setItem(i - 1, j, checkItem);
    }
}

void MainWindow::on_actSave_triggered()//另存为
{
    QString curPath = QCoreApplication::applicationDirPath();
    QString name = QFileDialog::getSaveFileName(this, "数据信息保存", curPath, "文本文件(*.txt)");
    if (name.isEmpty()) {
        return;
    }
    QFile file(name);
    if (file.open(QIODevice::ReadWrite | QIODevice::Text | QIODevice::Truncate)) {
        QTextStream stream(&file);
        stream.setCodec("UTF-8");
        ui->plainTextEdit->clear();
        QString str = "";
        for (int i = 0; i < model->columnCount(); i++) {//写表头
            QStandardItem *item = model->horizontalHeaderItem(i);
            str += (item->text() + "\t\t");
        }
        stream << str << "\n";
        ui->plainTextEdit->appendPlainText(str);
        QString text = "";
        for (int i = 0; i < model->rowCount(); i++) {
            int j = 0;
            for (; j < model->columnCount() - 1; j++) {
                text += model->item(i, j)->text() + "\t\t";
            }
            text += model->item(i, j)->checkState() == Qt::Checked ? "1\n" : "0\n";
        }
        stream << text;
        stream.flush();
    }
}

void MainWindow::on_actAppend_triggered()//添加一行
{
    QList<QStandardItem *>itemList;
    for (int i = 0; i < model->columnCount() - 1; i++) {
        QStandardItem *item = new QStandardItem("0");
        itemList << item;
    }
//    QString data = model->headerData(model->columnCount() - 1, Qt::Horizontal).toString();//最后一列check列
    QStandardItem *item = new QStandardItem("1");
    item->setCheckState(Qt::Checked);
    itemList << item;
    model->appendRow(itemList);


    selectModel->clear();//设置选中当前行
    QModelIndex index = model->index(model->rowCount() - 1, 0);
    selectModel->setCurrentIndex(index, QItemSelectionModel::Rows);
}

void MainWindow::on_actInsert_triggered()//插入一行
{
    QList<QStandardItem *>itemList;
    for (int i = 0; i < model->columnCount() - 1; i++) {
        QStandardItem *item = new QStandardItem("0");
        itemList << item;
    }

    QStandardItem *item = new QStandardItem("1");
    item->setCheckState(Qt::Checked);
    itemList << item;
    int row = selectModel->currentIndex().row();
    model->insertRow(row, itemList);

    selectModel->clear();//设置选中当前行
    QModelIndex index = model->index(row, 0);
    selectModel->setCurrentIndex(index, QItemSelectionModel::Select);
}

void MainWindow::on_actDelete_triggered()//删除一行
{
    QModelIndex index = selectModel->currentIndex();
    model->removeRow(index.row());
    if (index.row() >= model->rowCount()) {
        index = model->index(model->rowCount() - 1, 0);
    }
    selectModel->setCurrentIndex(index, QItemSelectionModel::Select);
}

void MainWindow::setTextAlign(Qt::Alignment atextAlignment)//设置文本对齐方式
{
    if (selectModel->hasSelection()) {
        QModelIndexList selectList = selectModel->selectedIndexes();
        for (int i = 0; i < selectList.count(); i++) {
            QModelIndex index = selectList[i];
            QStandardItem *item = model->itemFromIndex(index);
            item->setTextAlignment(atextAlignment);
        }
    }
}

void MainWindow::on_actAlignLeft_triggered()//文本左对齐
{
    setTextAlign(Qt::AlignLeft);
}

void MainWindow::on_actAlignCenter_triggered()
{
    setTextAlign(Qt::AlignCenter);
}

void MainWindow::on_actAlignRight_triggered()
{
    setTextAlign(Qt::AlignRight);
}

void MainWindow::on_actFontBold_triggered(bool checked)//字体加粗
{
    if (selectModel->hasSelection()) {
        QModelIndexList selectList = selectModel->selectedIndexes();
        for (int i = 0; i < selectList.count(); i++) {
            QModelIndex index = selectList[i];
            QStandardItem *item = model->itemFromIndex(index);
            QFont font = item->font();
            font.setBold(checked);
            item->setFont(font);
        }
    }
}

界面
image

posted @ 2023-03-16 10:46  echo_lovely  阅读(160)  评论(0编辑  收藏  举报