pyqt5中qtablewidget的用法
时间: 2023-09-21 12:10:49 浏览: 102
PyQt5高级界面控件之QTableWidget的具体使用方法
QTableWidget是PyQt5中的一个表格控件,可用于显示和编辑表格数据。以下是QTableWidget的基本用法:
1. 创建QTableWidget对象:
```python
tableWidget = QTableWidget()
```
2. 设置表格的行数和列数:
```python
tableWidget.setRowCount(rows)
tableWidget.setColumnCount(columns)
```
3. 设置表格的表头:
```python
tableWidget.setHorizontalHeaderLabels(horizontal_labels)
tableWidget.setVerticalHeaderLabels(vertical_labels)
```
4. 设置表格的单元格内容:
```python
tableWidget.setItem(row_index, column_index, QTableWidgetItem(cell_value))
```
5. 获取表格的单元格内容:
```python
cell_value = tableWidget.item(row_index, column_index).text()
```
6. 设置表格的选择模式:
```python
tableWidget.setSelectionMode(QAbstractItemView.SingleSelection) # 单选模式
tableWidget.setSelectionMode(QAbstractItemView.MultiSelection) # 多选模式
tableWidget.setSelectionMode(QAbstractItemView.ExtendedSelection) # 扩展选择模式
```
7. 设置表格的编辑模式:
```python
tableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers) # 禁止编辑
tableWidget.setEditTriggers(QAbstractItemView.DoubleClicked) # 双击编辑
tableWidget.setEditTriggers(QAbstractItemView.SelectedClicked) # 单击编辑
tableWidget.setEditTriggers(QAbstractItemView.CurrentChanged) # 切换编辑
```
8. 设置表格的行高和列宽:
```python
tableWidget.setRowHeight(row_index, height) # 设置行高
tableWidget.setColumnWidth(column_index, width) # 设置列宽
```
9. 添加行和删除行:
```python
tableWidget.insertRow(row_index) # 添加行
tableWidget.removeRow(row_index) # 删除行
```
10. 保存表格数据到文件:
```python
with open('data.csv', 'w') as file:
writer = csv.writer(file)
for row_index in range(tableWidget.rowCount()):
row_data = []
for column_index in range(tableWidget.columnCount()):
cell_value = tableWidget.item(row_index, column_index).text()
row_data.append(cell_value)
writer.writerow(row_data)
```
11. 从文件加载表格数据:
```python
with open('data.csv', 'r') as file:
reader = csv.reader(file)
for row_index, row_data in enumerate(reader):
for column_index, cell_value in enumerate(row_data):
item = QTableWidgetItem(cell_value)
tableWidget.setItem(row_index, column_index, item)
```
阅读全文