一、创建QTableWidget对象,设置大小,在窗口的位置
//创建tablewidgetQTableWidget *table = new QTableWidget(this);table->resize(550, 300);table->move(100, 100); //移动
二、设置表头
//设置表头QStringList headerList; //定义headerList变量headerList << "姓名" << "班级" << "学号"; //添加内容QFont font; //设置字号font.setPointSize(17);table->setFont(font);table->setColumnCount(headerList.size()); //设置列数=表头列数table->setHorizontalHeaderLabels(headerList); //添加headerList到表头//ResizeToContents, 列的宽度会根据列标题文字的宽度设置table->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); //需要包含#include <QHeaderView>table->setRowCount(3); //设置行数,不设置显示不出文本
要注意设置行数和列数,不然不会显示内容或文本
三、往表格添加内容
//往表格添加内容QStringList nameList, classList, studentIDList;nameList << "陈*林" << "张三" << "李四";classList << "计算机科学与技术22(3)班" << "人工智能23(1)班" << "软件工程24(4)班";studentIDList << "2130602105" << "2340602143" << "2460602113";for(int i=0; i<headerList.size(); i++){QTableWidgetItem *nameItem = new QTableWidgetItem(nameList[i]); //创建列表项nameItem->setTextAlignment(Qt::AlignCenter);table->setItem(i, 0, nameItem);table->setRowHeight(i, 10); // 设置行大小QTableWidgetItem *classItem = new QTableWidgetItem(classList[i]); //创建列表项classItem->setTextAlignment(Qt::AlignCenter);table->setItem(i, 1, classItem);QTableWidgetItem *studentIDItem = new QTableWidgetItem(studentIDList[i]); //创建列表项studentIDItem->setTextAlignment(Qt::AlignCenter);table->setItem(i, 2, studentIDItem);}
【完整代码】
#include "widget.h"
#include "ui_widget.h"
#include <QTableWidget>
#include <QHeaderView>
#include <QDebug>Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget)
{ui->setupUi(this);//创建tablewidgetQTableWidget *table = new QTableWidget(this);table->resize(550, 300);table->move(100, 100); //移动//设置表头QStringList headerList; //定义headerList变量headerList << "姓名" << "班级" << "学号"; //添加内容QFont font; //设置字号font.setPointSize(17);table->setFont(font);table->setColumnCount(headerList.size()); //设置列数=表头列数table->setHorizontalHeaderLabels(headerList); //添加headerList到表头//ResizeToContents, 列的宽度会根据列标题文字的宽度设置table->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); //需要包含#include <QHeaderView>table->setRowCount(3); //设置行数,不设置显示不出文本//往表格添加内容QStringList nameList, classList, studentIDList;nameList << "王五" << "张三" << "李四";classList << "计算机科学与技术22(3)班" << "人工智能23(1)班" << "软件工程24(4)班";studentIDList << "2130602105" << "2340602143" << "2460602113";for(int i=0; i<headerList.size(); i++){QTableWidgetItem *nameItem = new QTableWidgetItem(nameList[i]); //创建列表项nameItem->setTextAlignment(Qt::AlignCenter);table->setItem(i, 0, nameItem);table->setRowHeight(i, 10); // 设置行大小QTableWidgetItem *classItem = new QTableWidgetItem(classList[i]); //创建列表项classItem->setTextAlignment(Qt::AlignCenter);table->setItem(i, 1, classItem);QTableWidgetItem *studentIDItem = new QTableWidgetItem(studentIDList[i]); //创建列表项studentIDItem->setTextAlignment(Qt::AlignCenter);table->setItem(i, 2, studentIDItem);}
}Widget::~Widget()
{delete ui;
}