QTableView添加Item
时间: 2024-06-21 16:03:32 浏览: 8
在Qt中,`QTableView` 是用于显示表格数据的控件,如果你想向其添加新的行(Item),通常你会使用 `model`(数据模型)来管理数据,而不是直接在视图上操作。以下是一个基本步骤:
1. 创建数据模型(如 `QStandardItemModel` 或 `QSqlTableModel`):
```cpp
QStandardItemModel *model = new QStandardItemModel(this);
```
2. 添加行到模型:
```cpp
// 用元组或列表创建数据
QStringList data = {"列1", "列2", "列3"};
QStandardItem *item = new QStandardItem(data); // 创建一个单元格
for (int i = 1; i < data.count(); ++i) {
item->appendRow(new QStandardItem(data[i])); // 添加子项
}
// 将新行添加到模型的最后一行
model->appendRow(item);
```
3. 将模型关联到 `QTableView`:
```cpp
QTableView *tableView = new QTableView(this);
tableView->setModel(model); // 设置模型为视图的数据源
```
4. 显示表格:
```cpp
QVBoxLayout *layout = new QVBoxLayout();
layout->addWidget(tableView);
QWidget *parentWidget = new QWidget();
parentWidget->setLayout(layout);
parentWidget->show(); // 显示父窗口
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)