feat: QTableWidget

QTableWidget(表格/数据表)的介绍和使用:
This commit is contained in:
touwoyimuli 2019-09-11 00:33:03 +08:00
parent 56ac97ca4c
commit d8676a8ebe
9 changed files with 807 additions and 0 deletions

View File

@ -0,0 +1,248 @@
#include "ExQTableWidget.h"
#include "ui_ExQTableWidget.h"
ExQTableWidget::ExQTableWidget(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::ExQTableWidget)
{
ui->setupUi(this);
setWindowTitle(QObject::tr("QTableWidget的讲解和使用"));
m_labCellIndex = new QLabel("当前单元格坐标:", this); //状态栏初始化
m_labCellIndex->setMinimumWidth(250);
m_labCellType = new QLabel("当前单元格类型:", this);
m_labCellType->setMinimumWidth(200);
m_labStudID = new QLabel("学生ID", this);
m_labStudID->setMinimumWidth(200);
ui->statusBar->addWidget(m_labCellIndex);
ui->statusBar->addWidget(m_labCellType);
ui->statusBar->addWidget(m_labStudID);
ui->chkBoxHeadEdit->setChecked(Qt::Unchecked);
setCentralWidget(ui->splitter_2);
on_btnSetHeader_clicked();
}
ExQTableWidget::~ExQTableWidget()
{
delete ui;
}
void ExQTableWidget::createItemsARow(int row, QString name, QString sex, QDate birth, QString nation, int score, bool isAnime)
{
QTableWidgetItem* item = nullptr;
int stunID = 20190913;
QString str = "";
item = new QTableWidgetItem(name, cellType::ctName); //创建name 坐标为(0, 0)的item
item->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); //文本显示居中
stunID += row; //学号 = 基数 + 行号
item->setData(Qt::UserRole, QVariant(stunID)); //设置stunID为data
ui->tableWidget->setItem(row, fieldColNum::colName, item); //插入item到tableWidget里面
item = new QTableWidgetItem(sex, cellType::ctSex); //性别
QIcon icon;
if (sex == "")
icon.addFile(":/images/Image002.ico");
else
icon.addFile(":/images/Image003.ico");
item->setIcon(icon);
item->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
ui->tableWidget->setItem(row, fieldColNum::colSex, item);
item = new QTableWidgetItem(birth.toString("yyyy-MM-dd"), cellType::ctBirth);//出生日期
item->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
ui->tableWidget->setItem(row, fieldColNum::colBirth, item);
item = new QTableWidgetItem(nation, cellType::ctNation); //籍贯
item->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
ui->tableWidget->setItem(row, fieldColNum::colNation, item);
item = new QTableWidgetItem(str.setNum(score), cellType::ctScore);//成绩
item->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
ui->tableWidget->setItem(row, fieldColNum::colScore, item);
item = new QTableWidgetItem("喜欢", cellType::ctLikeAnime); //喜欢二次元否?
if (isAnime)
item->setCheckState(Qt::Checked);
else
item->setCheckState(Qt::Unchecked);
item->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
item->setBackgroundColor(Qt::gray);
ui->tableWidget->setItem(row, fieldColNum::colLikeAnime, item);
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//设置表头
void ExQTableWidget::on_btnSetHeader_clicked()
{
QTableWidgetItem* item = nullptr;
QStringList list;
list << "姓名" << "性别" << "出生日期" << "籍贯" << "分数" << "是否喜欢二次元";
// ui->tableWidget->setHorizontalHeaderLabels(list); //只是初始化表头的每一列的名字
ui->tableWidget->setColumnCount(list.count());
for (int i = 0; i < ui->tableWidget->columnCount(); i++) {
item = new QTableWidgetItem(list.at(i)); //创建一个item
QFont font;
font.setBold(true);
font.setPointSize(12);
item->setFont(font); //设置item的字体颜色粗体大小
item->setTextColor(Qt::red);
ui->tableWidget->setHorizontalHeaderItem(i, item); //添加item到tableWidget
}
}
//初始化数据表
void ExQTableWidget::on_btnInitTable_clicked()
{
QTime time;
time = QTime::currentTime();
qsrand(static_cast<uint>(time.msec() + time.second() * 1000));
QString name = "学生";
QString sex = "保密";
QDate birth(2019, 9, 12);
QString nation = "武汉";
int score = 87;
bool isAnime = true;
ui->tableWidget->clearContents(); //清除工作区,不清除表头
int row = ui->tableWidget->rowCount();
for (int i = 0; i < row; i++) { //初始化一行行的数据
name = "学生";
name += QString::number(i);
int n = qrand() % 2; //产生随机数小于2
if (n == 0) {
sex = "";
isAnime = true;
}
else {
sex = "";
isAnime = false;
}
score += 10;
birth = birth.addDays(30);
createItemsARow(i, name, sex, birth, nation, score, isAnime);
}
}
//设置表格的行数
void ExQTableWidget::on_btnSetRow_clicked()
{
int n = ui->spinBoxRow->value();
ui->tableWidget->setRowCount(n);
}
//插入行
void ExQTableWidget::on_btnInsertRow_clicked()
{
int currRow = ui->tableWidget->currentRow();
ui->tableWidget->insertRow(currRow); //插入一行不会自动为单元格创建item
createItemsARow(currRow, "插入学生", "", QDate(2020, 07, 17), "楚国", 87, true);
}
//在最后一行添加一行
void ExQTableWidget::on_btnAddRow_clicked()
{
int row = ui->tableWidget->rowCount();
ui->tableWidget->insertRow(row);
createItemsARow(row, "添加学生", "", QDate(2021, 07, 17), "唐朝", 93, true);
}
//删除当前行
void ExQTableWidget::on_btnDelRow_clicked()
{
int currRow = ui->tableWidget->currentRow();
ui->tableWidget->removeRow(currRow); //删除当前行以及其他items
}
//自动设置行高
void ExQTableWidget::on_btnAutoHeight_clicked()
{
ui->tableWidget->resizeRowsToContents(); //自动调整所有行的内容,以适应内容高度
}
//自动设置列高
void ExQTableWidget::on_btnAutoWidth_clicked()
{
ui->tableWidget->resizeColumnsToContents(); //自动调整所有列的内容,以适应内容宽度
}
//读取表格内容到文本
void ExQTableWidget::on_btnReadToEdit_clicked()
{
QTableWidgetItem* item = nullptr;
QString str = "";
for (int i = 0; i < ui->tableWidget->rowCount(); i++) {
str = "";
for (int j = 0; j < ui->tableWidget->columnCount() - 1; j++) {
item = ui->tableWidget->item(i, j);
str += item->text() + " ";
}
item = ui->tableWidget->item(i, fieldColNum::colLikeAnime);
if (item->checkState() == Qt::Checked)
str += "喜欢二次元";
else
str += "不喜欢二次元";
ui->plainTextEdit->appendPlainText(str);
}
}
//表格可编辑模式
void ExQTableWidget::on_chkBoxHeadEdit_clicked(bool checked)
{
if (checked)
ui->tableWidget->setEditTriggers(QAbstractItemView::DoubleClicked | QAbstractItemView::SelectedClicked);
else
ui->tableWidget->setEditTriggers(QAbstractItemView::DoubleClicked);
}
//间隔行底色
void ExQTableWidget::on_chkBoxRowColor_clicked(bool checked)
{
ui->tableWidget->setAlternatingRowColors(checked);
}
//显示行表头
void ExQTableWidget::on_chkBoxHeadRow_clicked(bool checked)
{
ui->tableWidget->horizontalHeader()->setVisible(checked);
}
//显示列表头
void ExQTableWidget::on_chkBoxHeadCol_clicked(bool checked)
{
ui->tableWidget->verticalHeader()->setVisible(checked);
}
//单元格选择
void ExQTableWidget::on_radioBtnSelectItem_clicked()
{
ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectItems);
}
//行选择
void ExQTableWidget::on_radioBtnSelectRow_clicked()
{
ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
}
//获取当前item和前一个(点击)item的行列号
void ExQTableWidget::on_tableWidget_currentCellChanged(int currentRow, int currentColumn, int previousRow, int previousColumn)
{
m_labCellIndex->setText("当前单元格坐标:[" + QString::number(currentRow) + "行, " + QString::number(currentColumn) + "列]");
QTableWidgetItem* item = ui->tableWidget->item(currentRow, currentColumn);
int type = item->type();
m_labCellType->setText("当前单元格类型:" + QString::number(type));
QTableWidgetItem* item2 = ui->tableWidget->item(currentRow, fieldColNum::colName);
m_labStudID->setText("学生ID" + item2->data(Qt::UserRole).toString());
}

View File

@ -0,0 +1,82 @@
#ifndef EXQTABLEWIDGET_H
#define EXQTABLEWIDGET_H
#include <QMainWindow>
#include <QLabel>
#include <QTime>
namespace Ui {
class ExQTableWidget;
}
class ExQTableWidget : public QMainWindow
{
Q_OBJECT
private:
enum cellType { //自定义表格单元格TYPE的类型,创建item时使用
ctName,
ctSex,
ctBirth,
ctNation,
ctScore,
ctLikeAnime
};
enum fieldColNum { //自定义各个表段在表格中的列号
colName,
colSex,
colBirth,
colNation,
colScore,
colLikeAnime
};
public:
explicit ExQTableWidget(QWidget *parent = nullptr);
~ExQTableWidget();
void createItemsARow(int row, QString name, QString sex, QDate birth, QString nation, int score, bool isAnime); //为某一行创建items
private slots:
void on_btnSetHeader_clicked();
void on_btnInitTable_clicked();
void on_btnSetRow_clicked();
void on_btnInsertRow_clicked();
void on_btnAddRow_clicked();
void on_btnDelRow_clicked();
void on_btnAutoHeight_clicked();
void on_btnAutoWidth_clicked();
void on_btnReadToEdit_clicked();
void on_chkBoxHeadEdit_clicked(bool checked);
void on_chkBoxRowColor_clicked(bool checked);
void on_chkBoxHeadRow_clicked(bool checked);
void on_chkBoxHeadCol_clicked(bool checked);
void on_radioBtnSelectItem_clicked();
void on_radioBtnSelectRow_clicked();
void on_tableWidget_currentCellChanged(int currentRow, int currentColumn, int previousRow, int previousColumn);
private:
Ui::ExQTableWidget *ui;
QLabel *m_labCellIndex; //状态栏上用来显示单元格的行号、列号
QLabel *m_labCellType; //状态栏上用来显示单元格的type
QLabel *m_labStudID; //状态栏上用来显示单元格的学号
};
#endif // EXQTABLEWIDGET_H

View File

@ -0,0 +1,415 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>ExQTableWidget</class>
<widget class="QMainWindow" name="ExQTableWidget">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>911</width>
<height>478</height>
</rect>
</property>
<property name="windowTitle">
<string>ExQTableWidget</string>
</property>
<widget class="QWidget" name="centralWidget">
<widget class="QSplitter" name="splitter_2">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>911</width>
<height>421</height>
</rect>
</property>
<property name="minimumSize">
<size>
<width>270</width>
<height>0</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>16777215</height>
</size>
</property>
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<widget class="QGroupBox" name="gridGroupBox">
<property name="minimumSize">
<size>
<width>270</width>
<height>0</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>320</width>
<height>16777215</height>
</size>
</property>
<layout class="QGridLayout" name="gridLayout">
<item row="2" column="1">
<widget class="QSpinBox" name="spinBoxRow">
<property name="value">
<number>20</number>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QPushButton" name="btnSetHeader">
<property name="text">
<string>设置表头</string>
</property>
</widget>
</item>
<item row="2" column="0">
<widget class="QPushButton" name="btnSetRow">
<property name="text">
<string>设置行数</string>
</property>
</widget>
</item>
<item row="5" column="0">
<widget class="QPushButton" name="btnAutoHeight">
<property name="text">
<string>自动调节表格的行高</string>
</property>
</widget>
</item>
<item row="3" column="1">
<widget class="QPushButton" name="btnAddRow">
<property name="text">
<string>添加行</string>
</property>
</widget>
</item>
<item row="3" column="0">
<widget class="QPushButton" name="btnInsertRow">
<property name="text">
<string>插入行</string>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QPushButton" name="btnInitTable">
<property name="text">
<string>初始化表格</string>
</property>
</widget>
</item>
<item row="4" column="1">
<widget class="QPushButton" name="btnReadToEdit">
<property name="text">
<string>读取表格内容到文本</string>
</property>
</widget>
</item>
<item row="4" column="0">
<widget class="QPushButton" name="btnDelRow">
<property name="text">
<string>删除当前行</string>
</property>
</widget>
</item>
<item row="5" column="1">
<widget class="QPushButton" name="btnAutoWidth">
<property name="text">
<string>自动调节表格的列高</string>
</property>
</widget>
</item>
<item row="6" column="1">
<widget class="QGroupBox" name="groupBoxSelect">
<property name="title">
<string>选择:</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QRadioButton" name="radioBtnSelectItem">
<property name="text">
<string>单元格选择</string>
</property>
<property name="checked">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QRadioButton" name="radioBtnSelectRow">
<property name="text">
<string>行选择</string>
</property>
</widget>
</item>
<item>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
</layout>
</widget>
</item>
<item row="6" column="0">
<widget class="QGroupBox" name="groupBoxShow">
<property name="title">
<string>显示:</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<widget class="QCheckBox" name="chkBoxHeadEdit">
<property name="text">
<string>表格可编辑模式</string>
</property>
<property name="checked">
<bool>false</bool>
</property>
<property name="tristate">
<bool>false</bool>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chkBoxRowColor">
<property name="text">
<string>间隔行底色</string>
</property>
<property name="tristate">
<bool>false</bool>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chkBoxHeadRow">
<property name="text">
<string>显示行表头</string>
</property>
<property name="checked">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chkBoxHeadCol">
<property name="text">
<string>显示列表头</string>
</property>
<property name="checked">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<spacer name="verticalSpacer_2">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
</layout>
</widget>
</item>
</layout>
</widget>
<widget class="QSplitter" name="splitter">
<property name="minimumSize">
<size>
<width>600</width>
<height>0</height>
</size>
</property>
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<widget class="QTableWidget" name="tableWidget">
<row>
<property name="text">
<string>行0</string>
</property>
</row>
<row>
<property name="text">
<string>行1</string>
</property>
</row>
<row>
<property name="text">
<string>行2</string>
</property>
</row>
<row>
<property name="text">
<string>行3</string>
</property>
</row>
<column>
<property name="text">
<string>列0</string>
</property>
</column>
<column>
<property name="text">
<string>列1</string>
</property>
</column>
<column>
<property name="text">
<string>列2</string>
</property>
</column>
<column>
<property name="text">
<string>列3</string>
</property>
</column>
<column>
<property name="text">
<string>列4</string>
</property>
</column>
<item row="0" column="0">
<property name="text">
<string>0, 0</string>
</property>
</item>
<item row="0" column="1">
<property name="text">
<string>0, 1</string>
</property>
</item>
<item row="0" column="2">
<property name="text">
<string>0, 2</string>
</property>
</item>
<item row="0" column="3">
<property name="text">
<string>0, 3</string>
</property>
</item>
<item row="0" column="4">
<property name="text">
<string>0, 4</string>
</property>
</item>
<item row="1" column="0">
<property name="text">
<string>1, 0</string>
</property>
</item>
<item row="1" column="1">
<property name="text">
<string>1, 1</string>
</property>
</item>
<item row="1" column="2">
<property name="text">
<string>1, 2</string>
</property>
</item>
<item row="1" column="3">
<property name="text">
<string>1, 3</string>
</property>
</item>
<item row="1" column="4">
<property name="text">
<string>1, 4</string>
</property>
</item>
<item row="2" column="0">
<property name="text">
<string>2, 0</string>
</property>
</item>
<item row="2" column="1">
<property name="text">
<string>2, 1</string>
</property>
</item>
<item row="2" column="2">
<property name="text">
<string>2, 2</string>
</property>
</item>
<item row="2" column="3">
<property name="text">
<string>2, 3</string>
</property>
</item>
<item row="2" column="4">
<property name="text">
<string>2, 4</string>
</property>
</item>
<item row="3" column="0">
<property name="text">
<string>3, 0</string>
</property>
</item>
<item row="3" column="1">
<property name="text">
<string>3, 1</string>
</property>
</item>
<item row="3" column="2">
<property name="text">
<string>3, 2</string>
</property>
</item>
<item row="3" column="3">
<property name="text">
<string>3, 3</string>
</property>
</item>
<item row="3" column="4">
<property name="text">
<string>3, 4</string>
</property>
</item>
</widget>
<widget class="QPlainTextEdit" name="plainTextEdit"/>
</widget>
</widget>
</widget>
<widget class="QMenuBar" name="menuBar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>911</width>
<height>23</height>
</rect>
</property>
</widget>
<widget class="QToolBar" name="mainToolBar">
<attribute name="toolBarArea">
<enum>TopToolBarArea</enum>
</attribute>
<attribute name="toolBarBreak">
<bool>false</bool>
</attribute>
</widget>
<widget class="QStatusBar" name="statusBar"/>
</widget>
<layoutdefault spacing="6" margin="11"/>
<resources/>
<connections/>
</ui>

View File

@ -0,0 +1,45 @@
#-------------------------------------------------
#
# Project created by QtCreator 2019-09-10T23:19:17
#
#-------------------------------------------------
QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = QtQTableWidgetEx
TEMPLATE = app
# The following define makes your compiler emit warnings if you use
# any feature of Qt which has been marked as deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS
# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
CONFIG += c++11
SOURCES += \
main.cpp \
ExQTableWidget.cpp
HEADERS += \
ExQTableWidget.h
FORMS += \
ExQTableWidget.ui
RC_ICONS += qt.ico
# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
RESOURCES += \
resoure.qrc

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

11
QtQTableWidgetEx/main.cpp Normal file
View File

@ -0,0 +1,11 @@
#include "ExQTableWidget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
ExQTableWidget w;
w.show();
return a.exec();
}

BIN
QtQTableWidgetEx/qt.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

View File

@ -0,0 +1,6 @@
<RCC>
<qresource prefix="/">
<file>images/Image002.ico</file>
<file>images/Image003.ico</file>
</qresource>
</RCC>