QTableView根据header的长度来设置列宽
要根据header的长度来设置QTableView的列宽,可以使用setColumnWidth()函数。以下是一个示例代码:
from PyQt5.QtWidgets import QApplication, QTableView, QHeaderView, QVBoxLayout, QWidget
app = QApplication([])
window = QWidget()
layout = QVBoxLayout(window)
table = QTableView()
layout.addWidget(table)
# 设置header的内容
header = QHeaderView()
header.setSectionResizeMode(QHeaderView.ResizeToContents)
header.setStretchLastSection(True)
table.setHorizontalHeader(header)
table.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
# 设置列宽
model = QStandardItemModel(0, 3)
model.setHorizontalHeaderLabels(["Header1", "Header2", "Header3"])
table.setModel(model)
for i in range(3):
model.setHeaderData(i, Qt.Horizontal, "Header" + str(i+1))
width = table.horizontalHeader().sectionSizeHint(i)
table.setColumnWidth(i, width)
window.show()
app.exec_()
在这个示例中,我们创建了一个QStandardItemModel,并设置了3个列的header。然后,我们使用sectionSizeHint()函数来获取header的长度,然后使用setColumnWidth()函数来设置列宽
原文地址: https://www.cveoy.top/t/topic/iXcH 著作权归作者所有。请勿转载和采集!