gpt4 book ai didi

python - 如何让布局自动填充窗口大小

转载 作者:太空宇宙 更新时间:2023-11-03 14:22:25 25 4
gpt4 key购买 nike

我有一个问题,当窗口改变大小时,布局无法自动填充窗口。那么如何让这个布局在窗口大小调整时填充窗口呢?

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_())

enter image description here

enter image description here

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

最佳答案

您不必创建新的小部件,您必须正确使用布局,首先将 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)

关于python - 如何让布局自动填充窗口大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47852697/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com