cpp, Qtablewidget 正确清理所有数据
时间: 2023-05-27 17:03:43 浏览: 59
要正确清理QTableWidget中的所有数据,可以使用以下代码:
```cpp
int rowCount = tableWidget->rowCount();
int columnCount = tableWidget->columnCount();
// 删除所有单元格中的数据
for (int row = 0; row < rowCount; ++row) {
for (int column = 0; column < columnCount; ++column) {
QTableWidgetItem *item = tableWidget->item(row, column);
if (item) {
delete item; // 删除当前单元格中的数据
tableWidget->setItem(row, column, nullptr); // 设置单元格为空
}
}
}
// 删除表头
tableWidget->horizontalHeader()->deleteLater();
tableWidget->verticalHeader()->deleteLater();
// 清空表格
tableWidget->clearContents();
// 删除所有行和列
while (tableWidget->rowCount() > 0) {
tableWidget->removeRow(0);
}
while (tableWidget->columnCount() > 0) {
tableWidget->removeColumn(0);
}
```
请注意,这段代码将删除表格中的所有数据和表头,并清空所有单元格。如果您只是想清空表格中的数据但保留表头和单元格,则只需使用以下代码:
```cpp
tableWidget->clearContents(); // 清空所有单元格中的数据
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)