如何让布局自动填充window大小

How to make layout automatically fill window size

我遇到一个问题,当 window 改变其大小时,布局无法自动填充 window。那么如何使此布局在 windows 调整大小时填充 window?

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(200,40)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.horizontalLayoutWidget = QtWidgets.QWidget(self.centralwidget)
        self.horizontalLayout = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget)
        self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
        self.label = QtWidgets.QLabel(self.horizontalLayoutWidget)
        self.label.setText("LABEL")
        self.horizontalLayout.addWidget(self.label)
        self.lineEdit = QtWidgets.QLineEdit(self.horizontalLayoutWidget)
        self.horizontalLayout.addWidget(self.lineEdit)

        MainWindow.setCentralWidget(self.centralwidget)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

我希望线条始终填充 window 的宽度。

您不必创建新的小部件,您必须正确使用布局,首先将 QLabel 和 QLineEdit 放在 QHBoxLayout 中。然后我们将带有 QSpacerItem 的布局放在 QVBoxLayout 中,如下所示:

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(200,40)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.vlayout = QtWidgets.QVBoxLayout(self.centralwidget)

        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setText("LABEL")
        self.horizontalLayout.addWidget(self.label)
        self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
        self.horizontalLayout.addWidget(self.lineEdit)
        self.vlayout.addLayout(self.horizontalLayout)
        spacerItem = QtWidgets.QSpacerItem(20, 245, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
        self.vlayout.addItem(spacerItem)

        MainWindow.setCentralWidget(self.centralwidget)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

另一种选择是使用 QFormLayout:

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(200,40)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        flayout = QtWidgets.QFormLayout(self.centralwidget)
        self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
        flayout.addRow("LABEL", self.lineEdit)
        MainWindow.setCentralWidget(self.centralwidget)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)