QT 视图(view)模型(model)汇总

QStringListModel和QListView

UI界面

widget头文件

#ifndef WIDGET_H
#define WIDGET_H#include <QStringList>
#include <QStringListModel>
#include <QWidget>QT_BEGIN_NAMESPACE
namespace Ui {
class Widget;
}
QT_END_NAMESPACEclass Widget : public QWidget {Q_OBJECTpublic:Widget(QWidget* parent = nullptr);~Widget();private slots:void on_pushButton_clicked();void on_pushButton_2_clicked();void on_checkBox_clicked(bool checked);void on_pushButton_3_clicked();void on_pushButton_4_clicked();void on_pushButton_5_clicked();void on_pushButton_6_clicked();void on_pushButton_8_clicked(bool checked);void on_pushButton_9_clicked();void on_pushButton_10_clicked();void on_listView_clicked(const QModelIndex& index);private:Ui::Widget* ui;QStringList m_strList;QStringListModel* m_model;
};
#endif // WIDGET_H

widget.cpp

#include "widget.h"
#include "ui_widget.h"
#include <QStandardItemModel>>
Widget::Widget(QWidget* parent): QWidget(parent), ui(new Ui::Widget)
{ui->setupUi(this);m_strList << "北京"<< "上海"<< "山西"<< "南京";m_model = new QStringListModel(this);m_model->setStringList(m_strList);ui->listView->setModel(m_model);ui->listView->setEditTriggers(QAbstractItemView::EditTrigger::DoubleClicked | QAbstractItemView::EditTrigger::SelectedClicked);
}Widget::~Widget()
{delete ui;
}void Widget::on_pushButton_clicked()
{m_model->setStringList(m_strList);
}void Widget::on_pushButton_2_clicked()
{m_model->removeRows(0, m_model->rowCount()); //删除行
}void Widget::on_checkBox_clicked(bool checked)
{if (checked) {ui->listView->setEditTriggers(QAbstractItemView::EditTrigger::DoubleClicked | QAbstractItemView::EditTrigger::SelectedClicked);} else {ui->listView->setEditTriggers(QAbstractItemView::EditTrigger::NoEditTriggers);}
}void Widget::on_pushButton_3_clicked()
{qDebug() << "行数" << m_model->rowCount();m_model->insertRow(m_model->rowCount()); //插入了行qDebug() << "插入后,行数" << m_model->rowCount();QModelIndex index = m_model->index(m_model->rowCount() - 1);m_model->setData(index, "new item", Qt::DisplayRole);ui->listView->setCurrentIndex(index);
}void Widget::on_pushButton_4_clicked()
{QModelIndex index = ui->listView->currentIndex();m_model->insertRow(index.row()); //可以插入行//    m_model->insertRows(index.row(), 0); //会把行给换掉m_model->setData(index, "insert item", Qt::DisplayRole);
}void Widget::on_pushButton_5_clicked()
{QModelIndex index;int curRow = ui->listView->currentIndex().row();m_model->moveRow(index, curRow, index, curRow - 1);
}void Widget::on_pushButton_6_clicked()
{QModelIndex index;int curRow = ui->listView->currentIndex().row();m_model->moveRow(index, curRow, index, curRow + 2); //下移需要加2 ,因为两个行号的号,程序会进行自动调整
}void Widget::on_pushButton_8_clicked(bool checked)
{if (checked) {m_model->sort(0, Qt::SortOrder::AscendingOrder); //升序} else {m_model->sort(0, Qt::SortOrder::DescendingOrder); //降序}
}void Widget::on_pushButton_9_clicked()
{ui->plainTextEdit->clear();
}void Widget::on_pushButton_10_clicked()
{ui->plainTextEdit->clear();QStringList tempList = m_model->stringList();for (int i = 0; i < tempList.count(); i++) {ui->plainTextEdit->appendPlainText(tempList.at(i));}
}void Widget::on_listView_clicked(const QModelIndex& index)
{QString str = QString::asprintf("模型索引: row %d,column = %d", index.row(), index.column());qDebug() << str;qDebug() << m_model->data(index, Qt::DisplayRole);
}

 ui_widget.h

/********************************************************************************
** Form generated from reading UI file 'widget.ui'
**
** Created by: Qt User Interface Compiler version 6.3.1
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/#ifndef UI_WIDGET_H
#define UI_WIDGET_H#include <QtCore/QVariant>
#include <QtWidgets/QApplication>
#include <QtWidgets/QCheckBox>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QGroupBox>
#include <QtWidgets/QListView>
#include <QtWidgets/QPlainTextEdit>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QSplitter>
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QWidget>QT_BEGIN_NAMESPACEclass Ui_Widget
{
public:QVBoxLayout *verticalLayout_2;QSplitter *splitter;QGroupBox *groupBox;QGridLayout *gridLayout;QCheckBox *checkBox;QPushButton *pushButton_4;QPushButton *pushButton_3;QListView *listView;QPushButton *pushButton;QPushButton *pushButton_5;QPushButton *pushButton_2;QPushButton *pushButton_8;QPushButton *pushButton_7;QPushButton *pushButton_6;QGroupBox *groupBox_2;QVBoxLayout *verticalLayout;QPushButton *pushButton_9;QPushButton *pushButton_10;QPlainTextEdit *plainTextEdit;void setupUi(QWidget *Widget){if (Widget->objectName().isEmpty())Widget->setObjectName(QString::fromUtf8("Widget"));Widget->resize(800, 600);verticalLayout_2 = new QVBoxLayout(Widget);verticalLayout_2->setObjectName(QString::fromUtf8("verticalLayout_2"));splitter = new QSplitter(Widget);splitter->setObjectName(QString::fromUtf8("splitter"));splitter->setOrientation(Qt::Horizontal);groupBox = new QGroupBox(splitter);groupBox->setObjectName(QString::fromUtf8("groupBox"));gridLayout = new QGridLayout(groupBox);gridLayout->setObjectName(QString::fromUtf8("gridLayout"));checkBox = new QCheckBox(groupBox);checkBox->setObjectName(QString::fromUtf8("checkBox"));checkBox->setChecked(true);checkBox->setTristate(false);gridLayout->addWidget(checkBox, 0, 2, 1, 1);pushButton_4 = new QPushButton(groupBox);pushButton_4->setObjectName(QString::fromUtf8("pushButton_4"));gridLayout->addWidget(pushButton_4, 1, 1, 1, 1);pushButton_3 = new QPushButton(groupBox);pushButton_3->setObjectName(QString::fromUtf8("pushButton_3"));gridLayout->addWidget(pushButton_3, 1, 0, 1, 1);listView = new QListView(groupBox);listView->setObjectName(QString::fromUtf8("listView"));gridLayout->addWidget(listView, 3, 0, 1, 3);pushButton = new QPushButton(groupBox);pushButton->setObjectName(QString::fromUtf8("pushButton"));gridLayout->addWidget(pushButton, 0, 0, 1, 1);pushButton_5 = new QPushButton(groupBox);pushButton_5->setObjectName(QString::fromUtf8("pushButton_5"));gridLayout->addWidget(pushButton_5, 2, 0, 1, 1);pushButton_2 = new QPushButton(groupBox);pushButton_2->setObjectName(QString::fromUtf8("pushButton_2"));gridLayout->addWidget(pushButton_2, 0, 1, 1, 1);pushButton_8 = new QPushButton(groupBox);pushButton_8->setObjectName(QString::fromUtf8("pushButton_8"));pushButton_8->setCheckable(true);pushButton_8->setChecked(false);gridLayout->addWidget(pushButton_8, 2, 2, 1, 1);pushButton_7 = new QPushButton(groupBox);pushButton_7->setObjectName(QString::fromUtf8("pushButton_7"));gridLayout->addWidget(pushButton_7, 1, 2, 1, 1);pushButton_6 = new QPushButton(groupBox);pushButton_6->setObjectName(QString::fromUtf8("pushButton_6"));gridLayout->addWidget(pushButton_6, 2, 1, 1, 1);splitter->addWidget(groupBox);groupBox_2 = new QGroupBox(splitter);groupBox_2->setObjectName(QString::fromUtf8("groupBox_2"));verticalLayout = new QVBoxLayout(groupBox_2);verticalLayout->setObjectName(QString::fromUtf8("verticalLayout"));pushButton_9 = new QPushButton(groupBox_2);pushButton_9->setObjectName(QString::fromUtf8("pushButton_9"));verticalLayout->addWidget(pushButton_9);pushButton_10 = new QPushButton(groupBox_2);pushButton_10->setObjectName(QString::fromUtf8("pushButton_10"));verticalLayout->addWidget(pushButton_10);plainTextEdit = new QPlainTextEdit(groupBox_2);plainTextEdit->setObjectName(QString::fromUtf8("plainTextEdit"));verticalLayout->addWidget(plainTextEdit);splitter->addWidget(groupBox_2);verticalLayout_2->addWidget(splitter);retranslateUi(Widget);QMetaObject::connectSlotsByName(Widget);} // setupUivoid retranslateUi(QWidget *Widget){Widget->setWindowTitle(QCoreApplication::translate("Widget", "Widget", nullptr));groupBox->setTitle(QCoreApplication::translate("Widget", "1", nullptr));checkBox->setText(QCoreApplication::translate("Widget", "\345\205\201\350\256\270\347\274\226\350\276\221", nullptr));pushButton_4->setText(QCoreApplication::translate("Widget", "\346\217\222\345\205\245\351\241\271", nullptr));pushButton_3->setText(QCoreApplication::translate("Widget", "\346\267\273\345\212\240\351\241\271", nullptr));pushButton->setText(QCoreApplication::translate("Widget", "\346\201\242\345\244\215\345\210\227\350\241\250", nullptr));pushButton_5->setText(QCoreApplication::translate("Widget", "\344\270\212\347\247\273", nullptr));pushButton_2->setText(QCoreApplication::translate("Widget", "\346\270\205\351\231\244\345\210\227\350\241\250", nullptr));pushButton_8->setText(QCoreApplication::translate("Widget", "\346\216\222\345\272\217", nullptr));pushButton_7->setText(QCoreApplication::translate("Widget", "\345\210\240\351\231\244\351\241\271", nullptr));pushButton_6->setText(QCoreApplication::translate("Widget", "\344\270\213\347\247\273", nullptr));groupBox_2->setTitle(QCoreApplication::translate("Widget", "2", nullptr));pushButton_9->setText(QCoreApplication::translate("Widget", "\346\270\205\347\251\272\346\226\207\346\234\254", nullptr));pushButton_10->setText(QCoreApplication::translate("Widget", "\346\230\276\347\244\272\346\225\260\346\215\256\346\250\241\345\236\213", nullptr));} // retranslateUi};namespace Ui {class Widget: public Ui_Widget {};
} // namespace UiQT_END_NAMESPACE#endif // UI_WIDGET_H

QTableview和QStandItemModel

UI界面

 mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFile>
#include <QFileDialog>
#include <QItemSelectionModel>
#include <QRegularExpression>
#include <QStringList>
MainWindow::MainWindow(QWidget* parent): QMainWindow(parent), ui(new Ui::MainWindow)
{ui->setupUi(this);labCurFile = new QLabel("当前文件", this);labCurFile->setMinimumWidth(200);labCellPos = new QLabel("当前单元格", this);labCellPos->setMinimumWidth(200);labCellText = new QLabel("单元格内容", this);labCellText->setMinimumWidth(200);ui->statusbar->addWidget(labCurFile);ui->statusbar->addWidget(labCellPos);ui->statusbar->addWidget(labCellText);m_model = new QStandardItemModel(2, FixedColumnCount, this);m_selection = new QItemSelectionModel(m_model, this);ui->tableView->setModel(m_model); //设置模型ui->tableView->setSelectionModel(m_selection); //设置选择的模型ui->tableView->setSelectionMode(QAbstractItemView::ExtendedSelection); //设置选择的方式ui->tableView->setSelectionBehavior(QAbstractItemView::SelectItems); //设置选择行为connect(m_selection, &QItemSelectionModel::currentChanged, this, &MainWindow::do_currentChanged);
}MainWindow::~MainWindow()
{delete ui;
}void MainWindow::initModelData(QStringList& list)
{int rowCount = list.size();qDebug() << "行数" << rowCount;m_model->setRowCount(rowCount - 1); //设置行数减一QString header = list.at(0);//通过正则表达式将数据分开QStringList headList = header.split(QRegularExpression(R"(\s+)"), Qt::SkipEmptyParts); // \s+匹配空字符m_model->setHorizontalHeaderLabels(headList);qDebug() << headList;QStandardItem* item;int j;for (int i = 1; i < rowCount; i++) {QString alineText = list.at(i);QStringList tempList = header.split(QRegularExpression(R"(\s+)"), Qt::SkipEmptyParts); // \s+匹配空字符for (j = 0; j < FixedColumnCount - 1; j++) {item = new QStandardItem(headList.at(j));m_model->setItem(i - 1, j, item);}item = new QStandardItem(list.at(j));item->setCheckable(true);item->setBackground(QBrush(Qt::yellow));if (tempList.at(j) == "0") {item->setCheckState(Qt::CheckState::Unchecked);} else {item->setCheckState(Qt::CheckState::Checked);}}
}void MainWindow::do_currentChanged(const QModelIndex& current, const QModelIndex& previous)
{Q_UNUSED(previous); //消除没有使用过的警告//当前改变触发qDebug() << "改变:" << previous.row() << previous.column(); //上次的位置if (current.isValid()) {labCellPos->setText(QString::fromStdString("当前单元格:%1行,%2列").arg(current.row()).arg(current.column()));QStandardItem* item = m_model->itemFromIndex(current);labCellText->setText("单元格内容: " + item->text());ui->pushButton_9->setChecked(item->font().bold());}
}void MainWindow::on_pushButton_clicked()
{QString curPath = QCoreApplication::applicationDirPath(); //获取当前应用程序的路径QString fileName = QFileDialog::getOpenFileName(this, "打开文件", "./", "数据文件(*.txt);;所有文件(*.*)");if (fileName.isEmpty())return;//不为空qDebug() << fileName;QFile f = QFile(fileName);if (!f.open(QIODevice::ReadOnly | QIODevice::Text))return;QStringList list;ui->plainTextEdit->clear();QTextStream astream(&f); //设置文件数据流,传入的是文本流while (!astream.atEnd()) {QString str = astream.readLine();ui->plainTextEdit->appendPlainText(str);list.append(str);}f.close();//    qDebug() << "加载完成" << list;labCurFile->setText("当前文件:" + fileName);ui->btn_add->setEnabled(true);ui->btn_insert->setEnabled(true);ui->btn_remove->setEnabled(true);initModelData(list);
}void MainWindow::on_pushButton_2_clicked()
{ui->plainTextEdit->clear();//处理表头QStandardItem* aitem;QString str;for (int i = 0; i < m_model->columnCount(); ++i) {aitem = m_model->horizontalHeaderItem(i);str += aitem->text();str += '\t';}ui->plainTextEdit->appendPlainText(str);//处理内容
}void MainWindow::on_btn_add_clicked()
{QList<QStandardItem*> list;QStandardItem* aitem;for (int i = 0; i < m_model->columnCount() - 1; ++i) {aitem = new QStandardItem("0");list << aitem;}QString str = m_model->headerData(m_model->columnCount() - 1, Qt::Horizontal).toString();aitem = new QStandardItem(str);aitem->setCheckable(true);aitem->setBackground(QBrush(Qt::yellow));list << aitem;m_model->insertRow(m_model->rowCount(), list);m_selection->clearSelection();m_selection->setCurrentIndex(m_model->index(m_model->rowCount() - 1, 0), QItemSelectionModel::Select); //选中
}void MainWindow::on_btn_insert_clicked()
{QList<QStandardItem*> list;QModelIndex index;QStandardItem* aitem;for (int i = 0; i < m_model->columnCount() - 1; ++i) {aitem = new QStandardItem("1");list << aitem;}QString str = m_model->headerData(m_model->columnCount() - 1, Qt::Horizontal).toString();aitem = new QStandardItem(str);aitem->setCheckable(true);aitem->setBackground(QBrush(Qt::yellow));list << aitem;index = m_selection->currentIndex();m_model->insertRow(index.row(), list);m_selection->clearSelection();m_selection->setCurrentIndex(index, QItemSelectionModel::Select); //选中
}void MainWindow::on_btn_remove_clicked()
{QModelIndex index = m_selection->currentIndex();//    m_model->setRowCount(m_model->rowCount());qDebug() << "当前行" << index.row();qDebug() << "行总数" << m_model->rowCount() - 1;if (index.row() != m_model->rowCount() - 1) {m_model->removeRow(index.row());m_selection->setCurrentIndex(index, QItemSelectionModel::Select);} else {m_model->removeRow(index.row());}
}void MainWindow::on_pushButton_6_clicked()
{if (!m_selection->hasSelection())return;QModelIndexList indexList = m_selection->selectedIndexes();for (auto index : indexList) {m_model->itemFromIndex(index)->setTextAlignment(Qt::AlignLeft | Qt::AlignVCenter);}
}void MainWindow::on_pushButton_8_clicked()
{if (!m_selection->hasSelection())return;QModelIndexList indexList = m_selection->selectedIndexes();for (auto index : indexList) {m_model->itemFromIndex(index)->setTextAlignment(Qt::AlignCenter | Qt::AlignVCenter);}
}void MainWindow::on_pushButton_7_clicked()
{if (!m_selection->hasSelection())return;QModelIndexList indexList = m_selection->selectedIndexes();for (auto index : indexList) {m_model->itemFromIndex(index)->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);}
}void MainWindow::on_pushButton_9_clicked(bool checked)
{if (!m_selection->hasSelection())return;QModelIndexList indexList = m_selection->selectedIndexes();for (auto index : indexList) {//        QFont font = m_model->itemFromIndex(index)->font();//        font.setBold(checked);//        m_model->itemFromIndex(index)->setFont(font);QFont f;f.setBold(checked);m_model->itemFromIndex(index)->setFont(f);}
}

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H#include <QItemSelectionModel>
#include <QLabel>
#include <QMainWindow>
#include <QModelIndex>
#include <QStandardItem>
#include <QStandardItemModel>
QT_BEGIN_NAMESPACE
namespace Ui {
class MainWindow;
}
QT_END_NAMESPACEclass MainWindow : public QMainWindow {Q_OBJECTpublic:MainWindow(QWidget* parent = nullptr);~MainWindow();private:Ui::MainWindow* ui;QLabel* labCurFile;QLabel* labCellPos;QLabel* labCellText;const int FixedColumnCount = 6;QStandardItemModel* m_model;QItemSelectionModel* m_selection;void initModelData(QStringList& lsit);
private slots:void do_currentChanged(const QModelIndex& current, const QModelIndex& previous);void on_pushButton_clicked();void on_pushButton_2_clicked();void on_btn_add_clicked();void on_btn_insert_clicked();void on_btn_remove_clicked();void on_pushButton_6_clicked();void on_pushButton_8_clicked();void on_pushButton_7_clicked();void on_pushButton_9_clicked(bool checked);
};
#endif // MAINWINDOW_H

QFileSystemModel模型

UI界面

 mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <QListView>
#include <QTableView>
#include <QTreeView>
MainWindow::MainWindow(QWidget* parent): QMainWindow(parent), ui(new Ui::MainWindow)
{ui->setupUi(this);model = new QFileSystemModel(this);ui->treeView->setModel(model);ui->listView->setModel(model);ui->tableView->setModel(model);model->setRootPath("./"); //需要设置结构目录 并不会改他自己的结构 QDir::currentPath() 不可以没有这行,作用是激活ui->treeView->setRootIndex(model->index(QDir::currentPath())); //需要这样设置才会改变真正的位置connect(ui->treeView, &QTreeView::clicked, ui->listView, &QListView::setRootIndex); //树结构点击,设置数结构点connect(ui->treeView, &QTreeView::clicked, ui->tableView, &QTableView::setRootIndex);
}MainWindow::~MainWindow()
{delete ui;
}void MainWindow::on_action_root_triggered()
{//设置根目录QString dir = QFileDialog::getExistingDirectory(this, "获取目录", "./");qDebug() << dir;if (dir.isEmpty())return;ui->listView->setRootIndex(model->index(dir)); //设置目录ui->tableView->setRootIndex(model->index(dir));ui->treeView->setRootIndex(model->index(dir));
}void MainWindow::on_radioButton_clicked()
{//显示目录和文件model->setFilter(QDir::Filter::Files | QDir::Filter::AllDirs | QDir::NoDotAndDotDot);ui->frame_2->setEnabled(true);
}void MainWindow::on_radioButton_2_clicked()
{//只显示目录model->setFilter(QDir::Filter::AllDirs | QDir::NoDotAndDotDot);ui->frame_2->setEnabled(false);
}void MainWindow::on_checkBox_clicked(bool checked)
{ui->comboBox_1->setEnabled(checked);ui->pushButton->setEnabled(checked);model->setNameFilterDisables(!checked);
}void MainWindow::on_pushButton_clicked()
{QStringList strlist = ui->comboBox_1->currentText().trimmed().split(";", Qt::SkipEmptyParts); //去掉两边空格,在按照;进行分割,不要空字符qDebug() << strlist;model->setNameFilters(strlist);
}void MainWindow::on_treeView_clicked(const QModelIndex& index)
{ui->label_file->setText(model->fileName(index));ui->label_path->setText(model->filePath(index));ui->label_type->setText(model->type(index));ui->checkBox_check->setChecked(model->isDir(index));int sz = model->size(index);if (sz < 1024) {ui->label_size->setText(QString("%1 KB").arg(sz));} else {//        ui->label_size->setText(QString("%1 mb").arg(sz / 1024.0)); //不能设置小数点位数显示ui->label_size->setText(QString::asprintf("%.1f mb", sz / 1024.0)); //可以设置打印自定义格式}
}

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H#include <QFileSystemModel>
#include <QMainWindow>QT_BEGIN_NAMESPACE
namespace Ui {
class MainWindow;
}
QT_END_NAMESPACEclass MainWindow : public QMainWindow {Q_OBJECTpublic:MainWindow(QWidget* parent = nullptr);~MainWindow();private slots:void on_action_root_triggered();void on_radioButton_clicked();void on_radioButton_2_clicked();void on_checkBox_clicked(bool checked);void on_pushButton_clicked();void on_treeView_clicked(const QModelIndex& index);private:Ui::MainWindow* ui;QFileSystemModel* model;
};
#endif // MAINWINDOW_H

总结

一般来说,设置视图模型的对应关系时,会给QTableView设置两个模型,一个是

QStandardItemModel 用于设置一些基本的数据信息,另一个是选择的模型
QItemSelectionModel 用于判断选中单元格的具体位置,几行几列,根据这个模型可以获取到数据。

定制窗口

ui文件

 mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include "tdialoglocate.h"#include "tdialogheader.h"
#include "tdialogsize.h"
#include <QItemSelectionModel>
#include <QLabel>
#include <QMainWindow>
#include <QStandardItemModel>
QT_BEGIN_NAMESPACE
namespace Ui {
class MainWindow;
}
QT_END_NAMESPACEclass MainWindow : public QMainWindow {Q_OBJECTpublic:MainWindow(QWidget* parent = nullptr);~MainWindow();private slots:void on_action_row_column_triggered();void on_action_title_triggered();void on_action_cell_triggered();void do_setCellText(int row, int col, QString& text);void on_tableView_clicked(const QModelIndex& index);void do_model_currentchanged(QModelIndex current, QModelIndex previous);signals:void cellIndexChanged(int row, int column);private:Ui::MainWindow* ui;TDialogSize* tdialogsize;QStandardItemModel* m_model;QItemSelectionModel* m_selection;TDialogHeader* tdialogheader = nullptr;TDialogLocate* tdialoglocate;QLabel* labelcellpos;QLabel* labeltext;
};
#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QItemSelectionModel>
MainWindow::MainWindow(QWidget* parent): QMainWindow(parent), ui(new Ui::MainWindow)
{ui->setupUi(this);m_model = new QStandardItemModel(4, 4, this);QStringList headers;headers << "姓名"<< "性别"<< "学号"<< "部门";m_model->setHorizontalHeaderLabels(headers);m_selection = new QItemSelectionModel(m_model);ui->tableView->setModel(m_model);ui->tableView->setSelectionModel(m_selection);this->setCentralWidget(ui->tableView);labelcellpos = new QLabel("当前单元格:", this);labelcellpos->setMinimumWidth(200);labeltext = new QLabel("当前文本:", this);labeltext->setMinimumWidth(200);ui->statusbar->addWidget(labelcellpos);ui->statusbar->addWidget(labeltext);connect(m_selection, &QItemSelectionModel::currentChanged, this, &MainWindow::do_model_currentchanged);
}MainWindow::~MainWindow()
{delete ui;
}void MainWindow::on_action_row_column_triggered()
{tdialogsize = new TDialogSize(this);tdialogsize->setWindowFlag(Qt::MSWindowsFixedSizeDialogHint); //设置固定的大小tdialogsize->setRowColumn(m_model->rowCount(), m_model->columnCount());int ret = tdialogsize->exec(); // 1是接收 0是拒绝if (ret == QDialog::Accepted) {m_model->setColumnCount(tdialogsize->columnCount());m_model->setRowCount(tdialogsize->rowCount());}delete tdialogsize;
}void MainWindow::on_action_title_triggered()
{if (tdialogheader == nullptr) {tdialogheader = new TDialogHeader(this);}QStringList strlist;for (int i = 0; i < m_model->columnCount(); i++) {strlist.append(m_model->headerData(i, Qt::Orientation::Horizontal, Qt::DisplayRole).toString()); //添加头部数据,在水平}tdialogheader->setHeaderList(strlist);int ret = tdialogheader->exec();if (ret == QDialog::Accepted) {strlist = tdialogheader->headerList();m_model->setHorizontalHeaderLabels(strlist);}
}void MainWindow::on_action_cell_triggered()
{tdialoglocate = new TDialogLocate(this);tdialoglocate->setAttribute(Qt::WA_DeleteOnClose, true); //关闭时,自动删除tdialoglocate->setWindowFlag(Qt::WindowType::WindowStaysOnTopHint); //窗口始终在上面显示//初始化对话框tdialoglocate->setSpinRange(m_model->rowCount(), m_model->columnCount());QModelIndex index = m_selection->currentIndex();if (index.isValid()) {qDebug() << "index = " << index.row() << " " << index.column();tdialoglocate->setSpinValue(index.row(), index.column());}connect(tdialoglocate, &TDialogLocate::changeCellText, this, &MainWindow::do_setCellText);connect(tdialoglocate, &TDialogLocate::changeActionEnable, ui->action_cell, &QAction::setEnabled);connect(this, &MainWindow::cellIndexChanged, tdialoglocate, &TDialogLocate::setSpinValue);tdialoglocate->show();
}void MainWindow::do_setCellText(int row, int col, QString& text)
{QModelIndex index = m_model->index(row, col);m_selection->clearSelection();m_selection->setCurrentIndex(index, QItemSelectionModel::SelectionFlag::Select);m_model->setData(index, text);
}void MainWindow::on_tableView_clicked(const QModelIndex& index)
{qDebug() << "点击了" << index.row() << " " << index.column();emit cellIndexChanged(index.row(), index.column());
}void MainWindow::do_model_currentchanged(QModelIndex current, QModelIndex previous)
{if (current.isValid()) {labelcellpos->setText(QString::asprintf("当前单元格是:%d行 %d列", current.row(), current.column()));}QStandardItem* model = m_model->itemFromIndex(current); //根据索引取itemlabeltext->setText("单元格内容: " + model->text());
}

tdialogheader.h

#ifndef TDIALOGHEADER_H
#define TDIALOGHEADER_H#include <QDialog>
#include <QStringList>
#include <QStringListModel>namespace Ui {
class TDialogHeader;
}class TDialogHeader : public QDialog {Q_OBJECTpublic:explicit TDialogHeader(QWidget* parent = nullptr);~TDialogHeader();void setHeaderList(QStringList& headers);QStringList headerList();private:Ui::TDialogHeader* ui;QStringListModel* m_model;
};#endif // TDIALOGHEADER_H

tdialogheader.cpp

#include "tdialogheader.h"
#include "ui_tdialogheader.h"TDialogHeader::TDialogHeader(QWidget* parent): QDialog(parent), ui(new Ui::TDialogHeader)
{ui->setupUi(this);m_model = new QStringListModel(this);ui->listView->setModel(m_model);
}TDialogHeader::~TDialogHeader()
{delete ui;
}void TDialogHeader::setHeaderList(QStringList& headers)
{m_model->setStringList(headers); // QStringList模型设置标头
}QStringList TDialogHeader::headerList()
{return m_model->stringList();
}

后续代码就不贴了,需要联系 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/16298.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

使用AOP切面对返回的数据进行脱敏的问题

1.注解类 import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target;/*** Author: xiaoxin* Date: 2023/7/21 17:15*/ Retention(RetentionPolicy.RUNTIME) Targe…

python文件处理方式

python文件处理方式 file open(D:\pythonText.txt, r, encodingUTF-8) print(file) # <_io.TextIOWrapper nameD:\\pythonText.txt moder encodingUTF-8> print(type(file)) # <class _io.TextIOWrapper>读取文件 file open(D:\pythonText.txt, r, encodingU…

3d软件动物生活习性仿真互动教学有哪些优势

软体动物是一类广泛存在于海洋和淡水环境中的生物&#xff0c;其独特的形态和生活习性给学生带来了新奇和有趣的学习主题&#xff0c;为了方便相关专业学科日常授课教学&#xff0c;web3d开发公司深圳华锐视点基于真实的软体动物&#xff0c;制作软体动物3D虚拟展示系统&#x…

【visual studio2019】如何打开即时窗口

在 Visual Studio2019 中打开即时窗口&#xff0c;有两种方法&#xff1a; 1、可以通过“调试”菜单&#xff0c;然后选择“窗口”下的“即时窗口”选项 2、直接使用快捷键“Ctrl Alt I” 此时即时窗口将显示在 Visual Studio2019 的底部。在即时窗口中&#xff0c;可以执…

Java读取及生成pb文件并转换jsonString

Java读取及生成pb文件并转换jsonString 1. 效果图2. 原理2.1 Protocol Buffers是什么2.2 支持的语言2.3 根据.proto生成.java2.4 初始化及构建pb&#xff0c;读取&#xff0c;转jsonString 3. 源码3.1 address.proto3.2 PbParseUtil.java 参考 读取pb及生成pb文件pb文件转换jso…

stable diffusion

一&#xff1a;安装。 stable diffusion 安装和使用全教程 - 知乎 Stable Diffusion安装 - 知乎 环境安装&#xff1a; 1&#xff1a;python 3.10安装。 Download Python | Python.org 切记要安装3.10版本&#xff0c;因为Stable diffusion是用3.10版本编写的&#xff0c;所…

【C++】 哈希

一、哈希的概念及其性质 1.哈希概念 在顺序结构以及平衡树中&#xff0c;元素关键码与其存储位置之间没有对应的关系&#xff0c;因此在查找一个元素时&#xff0c;必须要经过关键码的多次比较。比如顺序表需要从第一个元素依次向后进行查找&#xff0c;顺序查找时间复杂度为…

VS Code环境配置问题

VS Code 环境配置问题 文章目录 VS Code 环境配置问题配置 C问题解决不乱码只显示结果避免闪退&#xff0c;中文乱码 配置 Java下载 JDKJDK 环境配置安装插件 配置 C 跟着官网教程&#xff08;英文版&#xff09;和其他博客配置了一遍&#xff0c;却遇到了很多小问题&#xff…

MyBatis源码剖析之延迟加载源码细节

文章目录 什么是延迟加载&#xff1f;实现局部延迟加载全局延迟加载 延迟加载原理实现延迟加载原理&#xff08;源码剖析)Setting 配置加载&#xff1a;延迟加载代理对象创建注意事项 什么是延迟加载&#xff1f; 在开发过程中很多时候我们并不需要总是在加载⽤户信息时就⼀定…

Android 开发代码规范

一. AndroidStudio开发工具规范 使用最新的稳定版本.统一文件的编码格式为utf-8. 清除每个类里面的无效的import导包.代码样式统一,比如&#xff0c;tab缩进4个空格&#xff0c;或者 tab size等如果没有特殊情况使用默认的配置即可。每行字数每行字符数不得超过 160 字符&…

【100天精通python】Day20:文件及目录操作_os模块和os.psth模块,文件权限修改

目录 专栏导读 1 文件的目录操作 os模块的一些操作目录函数​编辑 os.path 模块的操作目录函数 2 相对路径和绝对路径 3 路径拼接 4 判断目录是否存在 5 创建目录、删除目录、遍历目录 专栏导读 专栏订阅地址&#xff1a;https://blog.csdn.net/qq_35831906/category_12…

Mysql-MVCC 并发版本控制

参考链接&#xff1a;一文读懂MVCC实现原理_Nicolos_Z的博客-CSDN博客 1.总述&#xff1a; MVCC 主要是InnoDB解决数据库事务读写&#xff0c;导致的脏读、重复读问题的处理方法。通过快照读的方式&#xff0c;提高数据库并发查询的能力。 2.MVCC的实现 实现MVCC主要用到了…

在OK3588板卡上部署模型实现人工智能OCR应用

一、主机模型转换 我们依旧采用FastDeploy来部署应用深度学习模型到OK3588板卡上 进入主机Ubuntu的虚拟环境 conda activate ok3588 安装rknn-toolkit2&#xff08;该工具不能在OK3588板卡上完成模型转换&#xff09; git clone https://github.com/rockchip-linux/rknn-to…

金蝶云星空任意文件读取漏洞复现(0day)

0x01 产品简介 金蝶云星空是一款云端企业资源管理&#xff08;ERP&#xff09;软件&#xff0c;为企业提供财务管理、供应链管理以及业务流程管理等一体化解决方案。金蝶云星空聚焦多组织&#xff0c;多利润中心的大中型企业&#xff0c;以 “开放、标准、社交”三大特性为数字…

ChatGPT伦理挑战:人工智能的权利与责任

&#x1f337;&#x1f341; 博主 libin9iOak带您 Go to New World.✨&#x1f341; &#x1f984; 个人主页——libin9iOak的博客&#x1f390; &#x1f433; 《面试题大全》 文章图文并茂&#x1f995;生动形象&#x1f996;简单易学&#xff01;欢迎大家来踩踩~&#x1f33…

HCIP期中实验

考试需求 1 、该拓扑为公司网络&#xff0c;其中包括公司总部、公司分部以及公司骨干网&#xff0c;不包含运营商公网部分。 2 、设备名称均使用拓扑上名称改名&#xff0c;并且区分大小写。 3 、整张拓扑均使用私网地址进行配置。 4 、整张网络中&#xff0c;运行 OSPF 协议…

实时协作:团队效率倍增的关键

实时协作是指团队在当前时刻共同完成项目的能力。无论是否使用技术&#xff0c;都能实现这一点。然而&#xff0c;随着远程工作的盛行&#xff0c;安全的协作工具被用来让团队成员在项目和一般业务之间保持联系和同步。 传统协作与实时协作的区别 两种类型的协作最明显的区别…

uniapp 微信小程序 navigationBarBackgroundColor 标题栏颜色渐变

大体思路&#xff1a; 第一步&#xff1a;“navigationStyle”:“custom” 第二步&#xff1a; template内 重点&#xff1a;给view添加ref“top” 第三步&#xff1a;添加渐变色样式 1、pages.json {"path" : "pages/user/user","style" : …

【玩转Linux】Linux输入子系统简介

(꒪ꇴ꒪ ),hello我是祐言博客主页&#xff1a;C语言基础,Linux基础,软件配置领域博主&#x1f30d;快上&#x1f698;&#xff0c;一起学习&#xff01;送给读者的一句鸡汤&#x1f914;&#xff1a;集中起来的意志可以击穿顽石!作者水平很有限&#xff0c;如果发现错误&#x…

拯救者Y9000K无线Wi-Fi有时不稳定?该如何解决?

由于不同品牌路由器的性能差异&#xff0c;无法完美兼容最新的无线网卡技术&#xff0c;在连接网络时&#xff08;特别是网络负载较大的情况下&#xff09;&#xff0c;可能会出现Wi-Fi信号断开、无法网络无法访问、延迟突然变大的情况&#xff1b;可尝试下面方法进行调整。 1…