pyside6如何增加QTableWidget的行和列
时间: 2025-01-22 16:50:41 浏览: 86
### PySide6 QTableWidget 动态添加行和列
在 PySide6 中,`QTableWidget` 组件允许通过编程方式动态地增加行和列。这可以通过调用 `insertRow()` 和 `insertColumn()` 方法来实现。
#### 插入新行
要向表格中插入新的行,可以使用如下方法:
```python
table_widget.insertRow(row_index)
```
其中 `row_index` 是指定的新行位置索引。如果希望在最后一行之后追加,则可以直接获取当前行数并作为参数传入:
```python
current_row_count = table_widget.rowCount()
table_widget.insertRow(current_row_count)
```
对于每一行中的单元格数据填充,可采用以下形式完成操作[^1]:
```python
item = QTableWidgetItem("Item Text")
table_widget.setItem(row, column, item)
```
#### 添加新列
同样地,在表单内新增一列的操作也很简单:
```python
table_widget.insertColumn(column_index)
```
这里 `column_index` 定义了新加入列的位置。为了给定的某一行某一特定位置设置内容项,依然沿用上述提到过的 `setItem()` 函数即可[^2]。
下面是完整的示例代码片段展示如何在一个已存在的 `QTableWidget` 实例里动态添加行列以及相应的内容条目:
```python
from PySide6.QtWidgets import QApplication, QWidget, QVBoxLayout, QTableWidget, QTableWidgetItem
app = QApplication([])
window = QWidget()
layout = QVBoxLayout()
# 初始化带有两行三列结构的表格部件对象
table_widget = QTableWidget(2, 3)
for row in range(table_widget.rowCount()):
for col in range(table_widget.columnCount()):
cell_item = QTableWidgetItem(f'Cell {row},{col}')
table_widget.setItem(row, col, cell_item)
# 向现有表格最后面再额外附加一行
new_row_position = table_widget.rowCount()
table_widget.insertRow(new_row_position)
# 设置该新增行第一个单元格内的文字信息
first_cell_of_new_row = QTableWidgetItem('New Row First Cell')
table_widget.setItem(new_row_position, 0, first_cell_of_new_row)
# 类似地扩展另一侧方向上的维度——即增补一整列
additional_column_location = table_widget.columnCount()
table_widget.insertColumn(additional_column_location)
# 更新所有现存记录对应到最新布局下的显示状态
for r in range(table_widget.rowCount()):
new_col_content = QTableWidgetItem(f'Extra Col-{r}')
table_widget.setItem(r, additional_column_location, new_col_content)
layout.addWidget(table_widget)
window.setLayout(layout)
window.show()
app.exec_()
```
此段程序首先建立了一个具有固定大小(2×3)初始框架的表格视图;接着分别演示了怎样在其基础上按需扩充横向纵向两个方面,并适当调整内部元素以适应变化后的整体架构[^3]。
阅读全文
相关推荐


















