QTableWidget是表格的一种表示,表格中的每一项都是用QTableWidgetItem来表示的。QTableWidget默认提供了水平表头和垂直表头,表头的索引从1开始。
我们先看看代码:
- #include <QApplication>
- #include <QTableWidget>
- #include <QHBoxLayout>
- int main(int argc, char** argv)
- {
- QApplication app(argc, argv);
- QTableWidget* tableWidget = new QTableWidget;
- tableWidget->setWindowTitle("QTableWidget");
- tableWidget->resize(350, 250);
- tableWidget->setRowCount(6);
- tableWidget->setColumnCount(3);
- /*
- QStringList header;
- header.append("One");
- header.append("Two");
- tableWidget->setHorizontalHeaderLabels(header);
- */
- tableWidget->setItem(0,0, new QTableWidgetItem("A"));
- tableWidget->setItem(1,0, new QTableWidgetItem("B"));
- tableWidget->setItem(2,0, new QTableWidgetItem("C"));
- tableWidget->setItem(3,0, new QTableWidgetItem("D"));
- tableWidget->setItem(4,0, new QTableWidgetItem("E"));
- tableWidget->setItem(0,1, new QTableWidgetItem(QIcon("images/data.png"), "data"));
- tableWidget->setItem(1,1, new QTableWidgetItem(QIcon("images/decision.png"), "decision"));
- tableWidget->setItem(2,1, new QTableWidgetItem(QIcon("images/document.png"), "document"));
- tableWidget->setItem(3,1, new QTableWidgetItem(QIcon("images/printer.png"), "printer"));
- tableWidget->setItem(4,1, new QTableWidgetItem(QIcon("images/process.png"), "process"));
- tableWidget->show();
- return app.exec();
- }
运行如下图:
把注释去掉,运行如下图:
我们通过setHorizontalHeaderLabels来更改了表头。