如何在水平布局中调整小部件的大小

How to adjust the size of a widget within a horizontal layout

我希望我所有的小部件在我放大 GUI 时改变长度(水平)window。现在,当我将 window 变大时,只有行编辑会改变大小。最重要的是,我希望我的按钮和组合框更长。

import sys
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QGridLayout, QWidget, QListWidget, QLineEdit, QHBoxLayout, QPushButton


class Window(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        centralWidget = QWidget()
        self.setCentralWidget(centralWidget)
        self.Search_Bar = QLineEdit(placeholderText="Search")
        self.Button = QPushButton('button')
        layout = QHBoxLayout(centralWidget)
        layout.addWidget(self.Button)
        layout.addWidget(self.Search_Bar)



if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

有 2 种可能的解决方案:

  • 通过将小部件添加到布局来设置相同的拉伸:

    layout.addWidget(self.Button, <b>stretch=1</b>)
    layout.addWidget(self.Search_Bar, <b>stretch=1</b>)
    
  • 设置QSizePolicy::Expanding on the horizontal component of the sizePolicy按钮:

    sp = self.Button.sizePolicy()
    sp.setHorizontalPolicy(QtWidgets.QSizePolicy.Expanding)
    self.Button.setSizePolicy(sp)