我正在尝试水平拉伸QTableWidget以适合窗口宽度,但是我找不到如何做到这一点。我是Qt的新手。
浮动的代码段和图像显示,在水平调整程序窗口大小时,QLineEdit会拉伸以适合窗口宽度,但QTableWidget不会。
import sys
from PySide2.QtWidgets import QApplication, QWidget, QVBoxLayout, QLineEdit, QTableWidget
app = QApplication(sys.argv)
win = QWidget()
win.setWindowTitle('test')
win.setMinimumWidth(400)
layV1 = QVBoxLayout()
win.setLayout(layV1)
entry = QLineEdit(win)
entry.setPlaceholderText('test entry widget')
layV1.addWidget(entry)
table = QTableWidget(win)
table.setRowCount(10)
table.setColumnCount(5)
layV1.addWidget(table)
win.show()
app.exec_()
您可以使用它来延伸最后一部分:
table.horizontalHeader().setStretchLastSection(True)
如果要拉伸特定的列,则需要使用QHeaderView。您的代码的快速示例。
headerView = QHeaderView(QtCore.Qt.Horizontal, table)
table.setHorizontalHeader(headerView)
headerView.setSectionResizeMode(2, QHeaderView.Stretch)
headerView.setSectionsClickable(True)
只需将2替换为所需的列即可拉伸!