qt create 给table widget表构造数据
时间: 2024-01-25 07:04:03 浏览: 98
QT处理Excel数据到Table Widget的四种方法
要给Qt中的QTableWidget构造数据,你可以使用以下步骤:
1. 创建QTableWidget对象并设置行数和列数:
```
QTableWidget *tableWidget = new QTableWidget();
tableWidget->setRowCount(5);
tableWidget->setColumnCount(3);
```
2. 设置表头:
```
QStringList headerLabels;
headerLabels << "Name" << "Age" << "Gender";
tableWidget->setHorizontalHeaderLabels(headerLabels);
```
3. 填充单元格数据:
```
tableWidget->setItem(0, 0, new QTableWidgetItem("John"));
tableWidget->setItem(0, 1, new QTableWidgetItem("30"));
tableWidget->setItem(0, 2, new QTableWidgetItem("Male"));
tableWidget->setItem(1, 0, new QTableWidgetItem("Mary"));
tableWidget->setItem(1, 1, new QTableWidgetItem("25"));
tableWidget->setItem(1, 2, new QTableWidgetItem("Female"));
// 依此类推
```
完整示例代码如下:
```
#include <QtWidgets/QApplication>
#include <QtWidgets/QTableWidget>
#include <QtWidgets/QTableWidgetItem>
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QTableWidget *tableWidget = new QTableWidget();
tableWidget->setRowCount(5);
tableWidget->setColumnCount(3);
QStringList headerLabels;
headerLabels << "Name" << "Age" << "Gender";
tableWidget->setHorizontalHeaderLabels(headerLabels);
tableWidget->setItem(0, 0, new QTableWidgetItem("John"));
tableWidget->setItem(0, 1, new QTableWidgetItem("30"));
tableWidget->setItem(0, 2, new QTableWidgetItem("Male"));
tableWidget->setItem(1, 0, new QTableWidgetItem("Mary"));
tableWidget->setItem(1, 1, new QTableWidgetItem("25"));
tableWidget->setItem(1, 2, new QTableWidgetItem("Female"));
// 依此类推
tableWidget->show();
return app.exec();
}
```
阅读全文