可以通过设置QTableWidgetItem的对齐方式来实现QTableWidget中内容的居中显示。具体步骤如下:
- 创建QTableWidgetItem对象时,设置其文本对齐方式为居中。
item = QTableWidgetItem(str(row[col]))
item.setTextAlignment(Qt.AlignCenter)
- 将QTableWidgetItem对象添加到QTableWidget中即可。
完整代码示例:
from PyQt5.QtWidgets import QApplication, QTableWidget, QTableWidgetItem, QWidget, QVBoxLayout
from PyQt5.QtCore import Qt
app = QApplication([])
window = QWidget()
tableWidget = QTableWidget()
tableWidget.setRowCount(0)
tableWidget.setColumnCount(3)
header = ['ID', 'Name', 'Age']
tableWidget.setHorizontalHeaderLabels(header)
data = [
['001', 'Tom', 20],
['002', 'Jerry', 18],
['003', 'Mickey', 22]
]
for row in data:
table_row = tableWidget.rowCount()
tableWidget.insertRow(table_row)
for col in range(len(row)):
item = QTableWidgetItem(str(row[col]))
# 设置单元格内容居中显示
item.setTextAlignment(Qt.AlignCenter)
tableWidget.setItem(table_row, col, item)
layout = QVBoxLayout()
layout.addWidget(tableWidget)
window.setLayout(layout)
window.show()
app.exec_()
运行结果如下图所示: