【问题标题】:PySide2, how to stretch the QTableWidget to fit Window witdh?PySide2,如何拉伸 QTableWidget 以适应窗口宽度?
【发布时间】:2020-01-15 04:32:45
【问题描述】:

我试图让 QTableWidget 水平拉伸以适应窗口宽度,但我找不到如何做到这一点。我是 Qt 的新手。

以下代码 sn-p 和图像显示,在水平调整程序窗口大小时,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_()

【问题讨论】:

    标签: python qt width pyside qtablewidget


    【解决方案1】:

    您可以使用它来拉伸最后一部分:

    table.horizontalHeader().setStretchLastSection(True) 
    

    如果要拉伸特定列,则需要使用 QHeaderView。 使用您的代码的快速示例。

    headerView = QHeaderView(QtCore.Qt.Horizontal, table)
    table.setHorizontalHeader(headerView)
    headerView.setSectionResizeMode(2, QHeaderView.Stretch)
    headerView.setSectionsClickable(True)
    

    只需将 2 替换为所需的列即可拉伸!

    【讨论】:

    • 实际上,这比我所要求的更适合我的用例,因此感谢您添加了有关拉伸特定列的 cmets。但是,为了完整起见,有没有办法让所有列一起拉伸以适应未使用的空间?
    • 嗨@NicolaMingotti!您可以通过复制以下行来做到这一点: headerView.setSectionResizeMode(COLUMN, QHeaderView.Stretch) 并放置另一列。在您的示例中,您可以将此行复制 5 次。不知道有没有更好的办法。
    • 嗨@AlexLaur,确认工作。谢谢你。我标记事情已解决。再见。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-23
    • 1970-01-01
    • 2020-09-26
    • 2013-05-06
    相关资源
    最近更新 更多