QTableWidget 冻结列
时间: 2023-10-04 12:13:51 浏览: 292
您可以通过设置 QTableWidget 的视口(viewport)和表头(header)来实现冻结列的效果。
具体实现步骤如下:
1. 设置 QTableWidget 的列宽,示例代码如下:
```python
table_widget.setColumnWidth(0, 100)
table_widget.setColumnWidth(1, 100)
table_widget.setColumnWidth(2, 100)
table_widget.setColumnWidth(3, 100)
table_widget.setColumnWidth(4, 100)
```
2. 获取 QTableWidget 的视口和表头,示例代码如下:
```python
viewport = table_widget.viewport()
header = table_widget.horizontalHeader()
```
3. 将表头添加到视口中,示例代码如下:
```python
viewport_layout = QVBoxLayout(viewport)
viewport_layout.addWidget(header)
```
4. 设置表头的位置,示例代码如下:
```python
header.setFixedHeight(header.height()) # 固定表头高度
header.move(viewport.x(), viewport.y()) # 设置表头位置
```
5. 设置视口的滚动条,示例代码如下:
```python
scroll_bar = QScrollBar(Qt.Horizontal, viewport)
scroll_bar.setMaximum(header.width() - viewport.width())
scroll_bar.sliderMoved.connect(lambda value: viewport.move(-value, viewport.y()))
viewport_layout.addWidget(scroll_bar)
```
这样,当您水平滚动 QTableWidget 时,冻结的列会一直显示在界面上。
完整的代码示例如下:
```python
from PyQt5.QtWidgets import QApplication, QTableWidget, QTableWidgetItem, QVBoxLayout, QHeaderView, QScrollBar
from PyQt5.QtCore import Qt
class FrozenTableWidget(QTableWidget):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.init_ui()
def init_ui(self):
self.setColumnCount(5)
self.setRowCount(10)
for row in range(10):
for col in range(5):
item = QTableWidgetItem(f'({row}, {col})')
self.setItem(row, col, item)
# 设置列宽
self.setColumnWidth(0, 100)
self.setColumnWidth(1, 100)
self.setColumnWidth(2, 100)
self.setColumnWidth(3, 100)
self.setColumnWidth(4, 100)
# 获取视口和表头
viewport = self.viewport()
header = self.horizontalHeader()
# 将表头添加到视口中
viewport_layout = QVBoxLayout(viewport)
viewport_layout.addWidget(header)
# 设置表头位置
header.setFixedHeight(header.height())
header.move(viewport.x(), viewport.y())
# 设置视口的滚动条
scroll_bar = QScrollBar(Qt.Horizontal, viewport)
scroll_bar.setMaximum(header.width() - viewport.width())
scroll_bar.sliderMoved.connect(lambda value: viewport.move(-value, viewport.y()))
viewport_layout.addWidget(scroll_bar)
if __name__ == '__main__':
app = QApplication([])
table = FrozenTableWidget()
table.show()
app.exec_()
```
阅读全文