首页 > 其他分享 >QT5笔记: 21. QStandardItemModel

QT5笔记: 21. QStandardItemModel

时间:2023-03-16 10:57:39浏览次数:43  
标签:index QT5 21 QStandardItemModel void item ui model MainWindow

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

标签:index,QT5,21,QStandardItemModel,void,item,ui,model,MainWindow
From: https://www.cnblogs.com/echo-lovely/p/17221476.html

相关文章

  • 6-21
    编写一个函数,统计一条英文句子中字母的个数,在主程序中实现输入输出。1#include<iostream>2#include<string>3#include<string.h>4#include<stdio.h>5......
  • QT5笔记: 22. 自定义代理
    代理作用:在界面发生编辑时可以指定编辑所用的组件,可以沟通Model和View自定义代理需要继承的基类和需要实现的方法使用步骤:继承QStyledItemDelegate,实现上面的四个......
  • [CISCN2021 Quals]upload
    文件上传打开题目直接给出了源码 <?php if(!isset($_GET["ctf"])){   highlight_file(__FILE__);   die(); } ​ if(isset($_GET["ctf"]))   $ctf......
  • P5219 无聊的水题 I
    P5219无聊的水题I计有标号树,容易想到\(\text{Prufer}\)序列,那么对于度数的限制即使,每一个数的出现次数要小于等于\(m-1\),且一定要有等于的,容斥一下,用小于等于\(m-1......
  • QT5笔记:18 QPainter基本绘图 完结撒花,感谢陪伴!!!
    代码#include"widget.h"#include"ui_widget.h"#include<QPainter>Widget::Widget(QWidget*parent):QWidget(parent),ui(newUi::Widget){......
  • QT5笔记: 16. 时间和定时器的常用功能
    例子#ifndefWIDGET_H#defineWIDGET_H#include<QTime>#include<QTimer>#include<QWidget>QT_BEGIN_NAMESPACEnamespaceUi{classWidget;}QT_END_NAM......
  • QT5笔记:10. 容器类的迭代
    1.这里指的是Java类型的迭代器,即使用方式和Java中一致代器的使用例子(适用于可读可写迭代器)QList<QString>list;//声明容器类list<<"A"<<"B"<<"C"<<"D";//......
  • QT5笔记:12. 字符串和数值之间的转换
    字符串与进制转换的例子/***@briefWidget::on_btnCalcHex_clicked从界面上获取十六进制字符串,然后转为十进制和二进制字符串写回界面*/voidWidget::on_btnCal......
  • QT5笔记:7. 自定义类、自定义信号及类的元对象信息
    自定义的QPerson类,需要继承QObject类qperson.h头文件#ifndefQPERSON_H#defineQPERSON_H#include<QObject>classQPerson:publicQObject{Q_OBJECT......
  • QT5笔记: 8. QT的全局变量(基本数据类型、函数、宏)
    这个头文件中存放着QT类库的一些全局定义,一般Qt类的头文件会包含这个头文件:基本数据类型函数宏数据类型:保证跨平台时各数据类型长度统一函数定义(一些数......