使用QTableWidget,初始化数据、设置列头及格式,设置行数,设置每个单元格的编辑,间隔行底色变换、行选择 ,模式,单元格选择模式、插入行 、追加行、删除行,单元格加图标,单元格显示checkbox并设置是否可编辑,自动调节行高、列宽,显示/隐藏 水平表头、垂直表头
.h文件
#ifndef TABLEWIDGETEXAMPLE_H
#define TABLEWIDGETEXAMPLE_H#include <QMainWindow>
#include <QLabel>namespace Ui {
class TableWidgetExample;
}class TableWidgetExample : public QMainWindow
{Q_OBJECTprivate:enum CellType{ctName=1000,ctSex,ctBirth,ctNation,ctPartyM,ctScore};//单元格类型 枚举enum FieldColNum{colName=0,colSex,colBirth,colNation,colScore,colPartyM};//列号QLabel *labCellIndex;QLabel *labCellType;QLabel *labStudID;void createItemsARow(int rowNo,QString name,QString sex,QDate birth,QString nation,bool isPM,int score);public:explicit TableWidgetExample(QWidget *parent = nullptr);~TableWidgetExample();private slots:void on_btnSetHeader_clicked();void on_btnSetRows_clicked();void on_btnIniData_clicked();void on_btnInsertRow_clicked();void on_btnAppendRow_clicked();void on_btnDelCurRow_clicked();void on_btnAutoHeight_clicked();void on_btnAutoWidth_clicked();void on_btnReadToEdit_clicked();void on_chkBoxTabEditable_clicked(bool checked);void on_chkBoxRowColor_clicked(bool checked);void on_chkBoxHeaderH_clicked(bool checked);void on_chkBoxHeaderV_clicked(bool checked);void on_rBtnSelectRow_clicked();void on_rBtnSelectItem_clicked();void on_tableInfo_currentCellChanged(int currentRow, int currentColumn, int previousRow, int previousColumn);private:Ui::TableWidgetExample *ui;
};#endif // TABLEWIDGETEXAMPLE_H
.cpp
#include "tablewidgetexample.h"
#include "ui_tablewidgetexample.h"#include <QDate>
#include <QTableWidgetItem>
#include <QRandomGenerator>//給制定行号单元格 根据字段内容填充
void TableWidgetExample::createItemsARow(int rowNo, QString name, QString sex, QDate birth, QString nation, bool isPM, int score)
{uint studID = 202105000;//学号前缀//姓名QTableWidgetItem *item = new QTableWidgetItem(name,TableWidgetExample::ctName);item->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);studID+=rowNo;item->setData(Qt::UserRole,QVariant(studID));ui->tableInfo->setItem(rowNo,TableWidgetExample::colName,item);//性别//://images/boy.icoQIcon icon;if(sex=="男")icon.addFile("://images/boy.ico");elseicon.addFile("://images/girl.ico");item = new QTableWidgetItem(sex,TableWidgetExample::ctSex);item->setIcon(icon);item->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);Qt::ItemFlags flags =Qt::ItemIsSelectable|Qt::ItemIsEnabled;item->setFlags(flags);ui->tableInfo->setItem(rowNo,TableWidgetExample::colSex,item);//出生日期QString str = birth.toString("yyyy-MM-dd");item = new QTableWidgetItem(str,TableWidgetExample::ctBirth);item->setTextAlignment(Qt::AlignLeft|Qt::AlignVCenter);ui->tableInfo->setItem(rowNo,TableWidgetExample::colBirth,item);//民族item= new QTableWidgetItem(nation,TableWidgetExample::ctNation);item->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);ui->tableInfo->setItem(rowNo,TableWidgetExample::colNation,item);//是否党员item = new QTableWidgetItem("党员",TableWidgetExample::ctPartyM);item->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);flags =Qt::ItemIsSelectable|Qt::ItemIsUserCheckable|Qt::ItemIsEnabled;item->setFlags(flags);if(isPM)item->setCheckState(Qt::Checked);elseitem->setCheckState(Qt::Unchecked);item->setBackground(QBrush(Qt::yellow));//设置背景色ui->tableInfo->setItem(rowNo,TableWidgetExample::colPartyM,item);//分数str.setNum(score);item = new QTableWidgetItem(str,TableWidgetExample::ctScore);item->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);ui->tableInfo->setItem(rowNo,TableWidgetExample::colScore,item);
}
TableWidgetExample::TableWidgetExample(QWidget *parent): QMainWindow(parent), ui(new Ui::TableWidgetExample)
{ui->setupUi(this);setCentralWidget(ui->mainSplitter);labCellIndex = new QLabel("当前单元格坐标",this);labCellIndex->setMinimumWidth(250);labCellType= new QLabel("当前单元格类型",this);labCellType->setMinimumWidth(200);labStudID= new QLabel("学生ID:",this);labStudID->setMinimumWidth(200);ui->statusbar->addWidget(labCellIndex);ui->statusbar->addWidget(labCellType);ui->statusbar->addWidget(labStudID);ui->tableInfo->setAlternatingRowColors(ui->chkBoxRowColor->isChecked());
}TableWidgetExample::~TableWidgetExample()
{delete ui;
}void TableWidgetExample::on_btnSetHeader_clicked()
{QStringList headerText;headerText<<"姓名"<<"性别"<<"出生日期"<<"民族"<<"分数"<<"是否党员";ui->tableInfo->setColumnCount(headerText.size());for(int i=0;i<ui->tableInfo->columnCount();i++){QTableWidgetItem *headerItem = new QTableWidgetItem(headerText.at(i));QFont font = headerItem->font();font.setBold(true);font.setPointSize(11);headerItem->setForeground(QBrush(Qt::red));headerItem->setFont(font);ui->tableInfo->setHorizontalHeaderItem(i,headerItem);}
}void TableWidgetExample::on_btnSetRows_clicked()
{ui->tableInfo->setRowCount(ui->spinRowCount->value());ui->tableInfo->setAlternatingRowColors(ui->chkBoxRowColor->isChecked());
}void TableWidgetExample::on_btnIniData_clicked()
{QDate birth(2001,5,1);ui->tableInfo->clearContents();for(int i=0;i<ui->tableInfo->rowCount();i++){QString strName =QString("学生%1").arg(i);QString sex = ((i%2)==0)?"男":"女";bool isParty = ((i%2)==0)?false:true;int score =QRandomGenerator::global()->bounded(60,100);createItemsARow(i,strName,sex,birth,"汉族",isParty,score);int addDays =QRandomGenerator::global()->bounded(1,90);birth=birth.addDays(addDays);}
}void TableWidgetExample::on_btnInsertRow_clicked()
{int curRow = ui->tableInfo->currentRow();ui->tableInfo->insertRow(curRow);createItemsARow(curRow,"新学生","男",QDate::fromString("2022-10-1","yyyy-M-d"),"苗族",true,88);
}void TableWidgetExample::on_btnAppendRow_clicked()
{int curRow= ui->tableInfo->rowCount();//当前行号ui->tableInfo->insertRow(curRow);createItemsARow(curRow,"新生","女",QDate::fromString("2022-6-1","yyyy-M-d"),"满族",true,98);
}void TableWidgetExample::on_btnDelCurRow_clicked()
{int curRow= ui->tableInfo->currentRow();//当前行号ui->tableInfo->removeRow(curRow);
}void TableWidgetExample::on_btnAutoHeight_clicked()
{ui->tableInfo->resizeRowsToContents();
}void TableWidgetExample::on_btnAutoWidth_clicked()
{ui->tableInfo->resizeColumnsToContents();
}void TableWidgetExample::on_btnReadToEdit_clicked()
{QTableWidgetItem *item;ui->textEdit->clear();for(int i=0;i<ui->tableInfo->rowCount();i++){QString str = QString::asprintf("Row %d:",i+1);for(int j=0;j<ui->tableInfo->columnCount()-1;j++){item= ui->tableInfo->item(i,j);str += QString("\t %1").arg(item->text());}item = ui->tableInfo->item(i,colPartyM);if(item->checkState()==Qt::Checked)str+=QString("\t %1").arg("党员");elsestr+=QString("\t %1").arg("群众");ui->textEdit->appendPlainText(str);}
}void TableWidgetExample::on_chkBoxTabEditable_clicked(bool checked)
{if(checked){ui->tableInfo->setEditTriggers(QAbstractItemView::DoubleClicked|QAbstractItemView::SelectedClicked);}else{ui->tableInfo->setEditTriggers(QAbstractItemView::NoEditTriggers);}
}void TableWidgetExample::on_chkBoxRowColor_clicked(bool checked)
{ui->tableInfo->setAlternatingRowColors(checked);
}void TableWidgetExample::on_chkBoxHeaderH_clicked(bool checked)
{ui->tableInfo->horizontalHeader()->setVisible(checked);
}void TableWidgetExample::on_chkBoxHeaderV_clicked(bool checked)
{ui->tableInfo->verticalHeader()->setVisible(checked);
}void TableWidgetExample::on_rBtnSelectRow_clicked()
{ui->tableInfo->setSelectionBehavior(QAbstractItemView::SelectRows);
}void TableWidgetExample::on_rBtnSelectItem_clicked()
{ui->tableInfo->setSelectionBehavior(QAbstractItemView::SelectItems);
}void TableWidgetExample::on_tableInfo_currentCellChanged(int currentRow, int currentColumn, int previousRow, int previousColumn)
{Q_UNUSED(previousRow);Q_UNUSED(previousColumn);QTableWidgetItem *item = ui->tableInfo->item(currentRow,currentColumn);if(item==nullptr)return;labCellIndex->setText(QString::asprintf("当前单元格坐标 %d 行 %d 列",currentRow,currentColumn));labCellType->setText(QString::asprintf("获取单元格的类型 %d",item->type()));labStudID->setText(QString::asprintf("学生ID:%d",item->data(Qt::UserRole).toUInt()));
}
效果
总结
1. 容易敲错 ItemIsEnabled
2. 因为win11的原因,在默认样式下,效果不显示 设置成了Fusion ,表格的间隔行颜色变换才生效;后续继续看下 样式