QTableWidget怎么设置居中显示
时间: 2024-02-25 13:52:00 浏览: 35
可以使用 QTableWidgetItem 的 setTextAlignment() 方法来设置 QTableWidget 中的文本居中显示。具体操作如下:
```python
from PyQt5.QtWidgets import QTableWidget, QTableWidgetItem, QHBoxLayout, QWidget
from PyQt5.QtCore import Qt
# 创建表格控件
table_widget = QTableWidget()
# 创建表格行和列
table_widget.setRowCount(2)
table_widget.setColumnCount(2)
# 设置表格内容
item1 = QTableWidgetItem("第一行第一列")
item1.setTextAlignment(Qt.AlignCenter) # 设置居中显示
table_widget.setItem(0, 0, item1)
item2 = QTableWidgetItem("第一行第二列")
item2.setTextAlignment(Qt.AlignCenter) # 设置居中显示
table_widget.setItem(0, 1, item2)
item3 = QTableWidgetItem("第二行第一列")
item3.setTextAlignment(Qt.AlignCenter) # 设置居中显示
table_widget.setItem(1, 0, item3)
item4 = QTableWidgetItem("第二行第二列")
item4.setTextAlignment(Qt.AlignCenter) # 设置居中显示
table_widget.setItem(1, 1, item4)
# 将表格控件添加至布局中
layout = QHBoxLayout()
widget = QWidget()
widget.setLayout(layout)
layout.addWidget(table_widget)
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![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)