c++ qt tableWidget
时间: 2023-12-01 14:05:10 浏览: 58
用qt利用tablewidget等控件
The QTableWidget class in Qt is used to display tabular data in a grid format. It is a subclass of the QTableView class and provides a user interface for editing and displaying data in a table.
To use the QTableWidget class, you first need to create an instance of the class and set the number of rows and columns using the setRowCount() and setColumnCount() functions. You can then populate the table with data using the setItem() function, which takes a QTableWidgetItem object as an argument.
Here is an example of how to create a QTableWidget and populate it with data:
```cpp
// Create a new QTableWidget with 3 rows and 2 columns
QTableWidget *tableWidget = new QTableWidget(3, 2);
// Set the headers for the table
tableWidget->setHorizontalHeaderLabels({"Name", "Age"});
// Populate the table with data
tableWidget->setItem(0, 0, new QTableWidgetItem("John"));
tableWidget->setItem(0, 1, new QTableWidgetItem("25"));
tableWidget->setItem(1, 0, new QTableWidgetItem("Mary"));
tableWidget->setItem(1, 1, new QTableWidgetItem("30"));
tableWidget->setItem(2, 0, new QTableWidgetItem("Bob"));
tableWidget->setItem(2, 1, new QTableWidgetItem("40"));
// Add the table to a layout or widget
layout->addWidget(tableWidget);
```
In this example, we created a new QTableWidget with 3 rows and 2 columns. We then set the horizontal headers using the setHorizontalHeaderLabels() function. Finally, we populated the table with data using the setItem() function and added the table to a layout or widget using the addWidget() function.
You can also customize the appearance and behavior of the QTableWidget by setting properties and connecting signals and slots. For example, you can set the selection mode using the setSelectionMode() function and connect the itemChanged() signal to a slot to handle changes to the data in the table.
阅读全文