我遇到一个问题,当窗口改变其大小时,布局无法自动填充窗口。那么当窗口调整大小时如何使这个布局填充窗口?
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_())
我希望线总是填充窗口的宽度。
答案 0 :(得分:1)
您不必创建新窗口小部件,必须正确使用布局,首先将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)