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();
}
后续代码就不贴了,需要联系