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_NAMESPACE
class Widget : public QWidget {
Q_OBJECT
public:
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_NAMESPACE
class 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);
} // setupUi
void 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 Ui
QT_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_NAMESPACE
class MainWindow : public QMainWindow {
Q_OBJECT
public:
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