PySide2,如何拉伸 QTableWidget 以适应 Window 宽度?

PySide2, how to stretch the QTableWidget to fit Window witdh?

我正在尝试让 QTableWidget 水平拉伸以适应 window 宽度,但我找不到如何操作。我是 Qt 的新手。

下面的代码片段和图像显示,在水平调整程序 window 时,QLineEdit 会拉伸以适应 window 宽度,但 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 替换为所需的列即可拉伸!