表格小部件为应用程序提供标准的表格显示功能。QTableWidget中的项由QTableWidgetItem提供。
如果你想要一个使用你自己的数据模型的表,你应该使用QTableView而不是这个类。
常用函数
- cellWidget(int row, int column) const:返回显示在给定行和列的单元格中的小部件;
- closePersistentEditor(QTableWidgetItem *item):关闭item的持久编辑器;
- column(const QTableWidgetItem *item) const:返回该项的列;
- columnCount() const:返回列数;
- currentColumn() const:返回当前项的列;
- currentItem() const:返回当前项;
- currentRow() const:返回当前行;
- editItem(QTableWidgetItem *item):如果项目是可编辑的,则开始编辑它;
- item(int row, int column) const:如果给定的行和列已经设置,则返回对应的项;否则返回nullptr;
- itemAt(const QPoint &point) const:返回指向给定点上的项的指针,如果point没有被表部件中的项覆盖,则返回nullptr;
- removeCellWidget(int row, int column):删除行和列指示的单元格上设置的小部件;
- row(const QTableWidgetItem *item) const:返回该项的行;
- rowCount() const:返回行数;
- setColumnCount(int columns):设置列数;
- setCurrentCell(int row, int column):将当前单元格设置为位置(行、列)处的单元格;
- setCurrentItem(QTableWidgetItem *item):将当前项设置为项;
- setHorizontalHeaderItem(int column, QTableWidgetItem *item):将“列”的水平标题项设置为“项”。如果有必要,列数会增加以适应项目。删除前一个首部项(如果有的话);
- setHorizontalHeaderLabels(const QStringList &labels):使用labels设置水平标题标签;
- setItem(int row, int column, QTableWidgetItem *item):将给定行和列的项设置为项;
- setRowCount(int rows):将这个表的模型中的行数设置为rows;
- setVerticalHeaderItem(int row, QTableWidgetItem *item):将行的垂直标题项设置为项;
- setVerticalHeaderLabels(const QStringList &labels):使用labels设置垂直标题标签;
- takeItem(int row, int column):从表中删除行和列的项,但不删除它;
信号
- cellActivated(int row, int column):当按行和列指定的单元被激活时,发出此信号;
- cellChanged(int row, int column):当由行和列指定的单元格中的项的数据发生更改时,就会发出此信号;
- cellClicked(int row, int column):每当单击表格中的一个单元格时,就会发出这个信号。指定的行和列是单击的单元格;
- cellDoubleClicked(int row, int column):每当双击表格中的一个单元格时,就会发出这个信号。指定的行和列是单击的单元格;
- cellEntered(int row, int column):当鼠标光标进入一个单元格时,就会发出这个信号。单元格由行和列指定;
- cellPressed(int row, int column):每当按下表格中的一个单元格时,就会发出这个信号。指定的行和列是按下的单元格;
- void currentCellChanged(int currentRow, int currentColumn, int previousRow, int previousColumn):每当当前单元格发生变化时,该信号就会发出。previousRow和previousColumn指定的单元格是之前获得焦点的单元格,currentRow和currentColumn指定的单元格是新的当前单元格;
- currentItemChanged(QTableWidgetItem *current, QTableWidgetItem *previous):每当当前元素发生变化时,就会发出这个信号。previous item是之前拥有焦点的项,current是新的当前项;
- itemActivated(QTableWidgetItem *item):当指定的元素被激活时,就会发出这个信号;
- itemChanged(QTableWidgetItem *item):每当item的数据发生变化时,就会发出这个信号;
- itemClicked(QTableWidgetItem *item):每当单击表中的某个元素时,就会发出这个信号。指定的项目是被单击的项目;
- itemDoubleClicked(QTableWidgetItem *item):每当双击表中的一个元素时,就会发出这个信号。指定的项是被双击的项;
- itemEntered(QTableWidgetItem *item):当鼠标光标进入某个元素时,就会发出这个信号。项目就是输入的项目;
- itemPressed(QTableWidgetItem *item):每当按下表中的一个元素时,就会发出这个信号。指定的项目是按下的项目;
- itemSelectionChanged():每当选择发生变化时,就会发出这个信号;
槽函数
- clear():删除视图中的所有项。这也将删除所有的选择和标题;
- clearContents():从视图中删除所有不在标题中的项。这也将删除所有的选择。表的维度保持不变;
- insertColumn(int column):在列处向表中插入一个空列;
- insertRow(int row):在表的row处插入一个空行;
- removeColumn(int column):从表中删除列及其所有项;
- removeRow(int row):从表中删除行及其所有项;
- scrollToItem(const QTableWidgetItem *item, QAbstractItemView::ScrollHint hint = EnsureVisible:如果需要,滚动视图以确保项目可见;
QTableWidgetItem
表项用于保存表小部件的信息片段。项目通常包含文本、图标或复选框
QTableWidgetItem类是一个方便类,它取代了Qt 3中的QTableItem类。它提供了一个与QTableWidget类一起使用的项。
QTableWidgetItem常用函数
- background() const:返回用于渲染项目背景的画笔;
- checkState() const:返回表项的已检状态;
- column() const:返回表中项的列。如果某项不在表中,这个函数将返回-1;
- data(int role) const:返回指定角色的项数据;
- flags() const:返回用于描述项的标志。它们决定是否可以检查、编辑和选择项目;
- font() const:返回用于渲染项目文本的字体;
- isSelected() const:如果选中项,则返回true,否则返回false;
- read(QDataStream &in):从流中读取项目;
- write(QDataStream &out) const:将项写入流输出;
- row() const:返回表中项目的行。如果某项不在表中,这个函数将返回-1;
- setCheckState(Qt::CheckState state):将表项的检查状态设置为state;
- setData(int role, const QVariant &value):为给定角色设置项的数据为指定的值;
- setFlags(Qt::ItemFlags flags):将项的标志设置为给定的标志。它们决定了是否可以选择或修改项;
- setText(const QString &text):将项的文本设置为指定的文本;
- setTextAlignment(int alignment):将项目文本的文本对齐方式设置为指定的对齐方式;
图示
代码示例
QTableWidgetDialog.h
#ifndef QTABLEWIDGETDIALOG_H
#define QTABLEWIDGETDIALOG_H#include <QDialog>
#include <QLabel>
namespace Ui
{class QTableWidgetDialog;
}enum CellType {ctName = 1000, ctSex, ctBirth, ctNation, ctPartyM, ctScore};
enum FieldColNum {colName=0, colSex, colBirth, colNation, colScore, colPartyM};class QTableWidgetDialog : public QDialog
{Q_OBJECTpublic:explicit QTableWidgetDialog(QWidget* parent = nullptr);~QTableWidgetDialog();void init();void createItemARow(int rowNo, QString name, QString sex, QDate birth, QString nation, bool isPm, int score);
private slots:void on_pbSetHeader_clicked();void on_pbInit_clicked();void on_pbSetCountRow_clicked();void on_pbGetData_clicked();void on_tableWidget_currentCellChanged(int currentRow, int currentColumn, int previousRow, int previousColumn);void on_pbInsertRow_clicked();void on_pbAddRow_clicked();void on_pbRemoveCurRow_clicked();void on_pbAutoRowh_clicked();void on_pbAutoColw_clicked();void on_checkBoxEdit_clicked(bool checked);void on_checkBoxRowHeader_clicked(bool checked);void on_checkBoxColHeader_clicked(bool checked);void on_checkBoxColor_clicked(bool checked);void on_radioButtonRow_clicked();void on_radioButtonItem_clicked();private:Ui::QTableWidgetDialog* ui;QLabel* labCellIndex;QLabel* labCellType;QLabel* labStudID;};#endif // QTABLEWIDGETDIALOG_H
QTableWidgetDialog.cpp
#include "QTableWidgetDialog.h"
#include "ui_QTableWidgetDialog.h"
#include <QDate>
#include <QIcon>
#include <QDebug>
QTableWidgetDialog::QTableWidgetDialog(QWidget* parent): QDialog(parent), ui(new Ui::QTableWidgetDialog)
{ui->setupUi(this);init();
}QTableWidgetDialog::~QTableWidgetDialog()
{delete ui;
}void QTableWidgetDialog::init()
{ui->spinBoxCount->setMaximum(10000);
}void QTableWidgetDialog::on_pbSetHeader_clicked()
{QTableWidgetItem* headerItem;QStringList headerText;headerText<<"姓名"<<"性别"<<"出生日期"<<"民族"<<"分数"<<"是否党员";ui->tableWidget->setColumnCount(headerText.count());ui->tableWidget->horizontalHeader()->setMinimumHeight(50);for(int i=0; i<ui->tableWidget->columnCount(); i++) {headerItem = new QTableWidgetItem(headerText.at(i));QFont font = headerItem->font();font.setBold(true);font.setPointSize(12);headerItem->setTextColor(Qt::red);//设置单元格显示字体headerItem->setFont(font);ui->tableWidget->setHorizontalHeaderItem(i, headerItem);}
}void QTableWidgetDialog::on_pbInit_clicked()
{QString strName, strSex;bool isParty = false;QDate birth;birth.setDate(1995, 1, 1);//清除表格数据区数据 但是不清除表头ui->tableWidget->clearContents();//返回数据区行数int rows = ui->tableWidget->rowCount();for(int i=0; i<rows; i++) {strName = QString::asprintf("学生%d", i);if((i % 2)==0) {strSex = "man";} else {strSex = "woman";}createItemARow(i, strName, strSex, birth, "汉族", isParty, 70);birth=birth.addDays(20);isParty = !isParty;}
}void QTableWidgetDialog::createItemARow(int rowNo, QString name, QString sex, QDate birth, QString nation, bool isPm, int score)
{QTableWidgetItem* item;QString str;uint studID = 201605000;item = new QTableWidgetItem(name, ctName);item->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);//设置单元格前景色// item->setForeground(Qt::darkGray);//设置一个图标// item->setIcon();//设置属性标记// item->setFlags(Qt::ItemIsSelectable);studID+=rowNo;item->setData(Qt::UserRole, QVariant(studID));ui->tableWidget->setItem(rowNo, colName, item);item = new QTableWidgetItem(sex, ctSex);item->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);ui->tableWidget->setItem(rowNo, colSex, item);str = birth.toString("yyyy-MM-dd");item = new QTableWidgetItem(str, ctBirth);item->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);ui->tableWidget->setItem(rowNo, colBirth, item);item = new QTableWidgetItem(nation, ctNation);item->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);ui->tableWidget->setItem(rowNo, colNation, item);str.setNum(score);item = new QTableWidgetItem(str, ctScore);item->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);ui->tableWidget->setItem(rowNo, colScore, item);item = new QTableWidgetItem("党员", ctPartyM);if(isPm) {//设置单元格勾选状态item->setCheckState(Qt::Checked);} else {item->setCheckState(Qt::Unchecked);}// //设置单元格背景颜色item->setBackground(Qt::yellow);item->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);ui->tableWidget->setItem(rowNo, colPartyM, item);
}void QTableWidgetDialog::on_pbSetCountRow_clicked()
{ui->tableWidget->setRowCount(ui->spinBoxCount->text().toInt());
}void QTableWidgetDialog::on_pbGetData_clicked()
{QString str;QTableWidgetItem* cellItem;ui->textEdit->clear();for(int i=0; i<ui->tableWidget->rowCount(); i++) {str = QString::asprintf("%d ", i+1);for(int j=0; j<ui->tableWidget->columnCount()-1; j++) {cellItem = ui->tableWidget->item(i, j);str = str+cellItem->text() + " ";}cellItem = ui->tableWidget->item(i, colPartyM);if(cellItem->checkState()==Qt::Checked) {str = str+tr("partyM");} else {str = str+tr("general");}ui->textEdit->append(str);}
}//单元格切换 触发该信号
void QTableWidgetDialog::on_tableWidget_currentCellChanged(int currentRow, int currentColumn, int previousRow, int previousColumn)
{QTableWidgetItem* curItem =ui->tableWidget->item(currentRow, currentColumn);if(curItem == NULL) {return;}QString curstr = QString::asprintf("currentRow currentColumn :%d ,%d", currentRow, currentColumn);QString prestr = QString::asprintf("previousRow previousColumn :%d,%d", previousRow, previousColumn);qDebug()<<"curstr"<<curstr<<"prestr"<<prestr;
}//插入
void QTableWidgetDialog::on_pbInsertRow_clicked()
{int curRow = ui->tableWidget->currentRow();ui->tableWidget->insertRow(curRow);createItemARow(curRow, "stu2", "man", QDate::fromString("1996-1-1", "yyyy-M-d"), "满族", false, 66);
}void QTableWidgetDialog::on_pbAddRow_clicked()
{int rowCounts = ui->tableWidget->rowCount();ui->tableWidget->insertRow(rowCounts);createItemARow(rowCounts, "stu1", "man", QDate::fromString("1996-1-1", "yyyy-M-d"), "满族", false, 55);
}void QTableWidgetDialog::on_pbRemoveCurRow_clicked()
{int curRow = ui->tableWidget->currentRow();ui->tableWidget->removeRow(curRow);
}void QTableWidgetDialog::on_pbAutoRowh_clicked()
{ui->tableWidget->resizeRowsToContents();
}void QTableWidgetDialog::on_pbAutoColw_clicked()
{ui->tableWidget->resizeColumnsToContents();
}void QTableWidgetDialog::on_checkBoxEdit_clicked(bool checked)
{if(checked) {//双击或者获取焦点后单击进入编辑状态ui->tableWidget->setEditTriggers(QAbstractItemView::DoubleClicked | QAbstractItemView::SelectedClicked);} else {ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);}
}void QTableWidgetDialog::on_checkBoxRowHeader_clicked(bool checked)
{ui->tableWidget->horizontalHeader()->setVisible(checked);
}void QTableWidgetDialog::on_checkBoxColHeader_clicked(bool checked)
{ui->tableWidget->verticalHeader()->setVisible(checked);
}void QTableWidgetDialog::on_checkBoxColor_clicked(bool checked)
{ui->tableWidget->setAlternatingRowColors(checked);
}void QTableWidgetDialog::on_radioButtonRow_clicked()
{ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
}void QTableWidgetDialog::on_radioButtonItem_clicked()
{ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectItems);
}