- 此问题在此处已有答案**:
How to make a Qt Widget grow with the window size?(4个答案)
4天前关闭。
我在Qt6 Designer中生成了一个简单的UI,它由QDialog
上的QGridLayout
(或QMainWindow
-问题似乎是相同的)组成。
现在,我想这个布局,以填补整个窗口的大小,并调整自己的大小时,窗口大小的变化。
我怎样才能做到这一点?
下面是我的示例应用程序,其中包含Qt Designer生成的代码以及我自己的一些代码来运行它:
import sys
from PySide6.QtCore import QRect, QCoreApplication, QMetaObject
from PySide6.QtWidgets import QApplication, QWidget, QGridLayout, QLabel, QLineEdit, QSizePolicy
class Ui_Dialog():
def setupUi(self, Dialog):
if not Dialog.objectName():
Dialog.setObjectName(u"Dialog")
Dialog.resize(400, 300)
self.gridLayoutWidget = QWidget(Dialog)
self.gridLayoutWidget.setObjectName(u"gridLayoutWidget")
self.gridLayoutWidget.setGeometry(QRect(10, 20, 341, 191))
self.gridLayout = QGridLayout(self.gridLayoutWidget)
self.gridLayout.setObjectName(u"gridLayout")
self.gridLayout.setContentsMargins(0, 0, 0, 0)
self.label = QLabel(self.gridLayoutWidget)
self.label.setObjectName(u"label")
self.gridLayout.addWidget(self.label, 0, 0, 1, 1)
self.label_2 = QLabel(self.gridLayoutWidget)
self.label_2.setObjectName(u"label_2")
self.gridLayout.addWidget(self.label_2, 1, 0, 1, 1)
self.lineEdit = QLineEdit(self.gridLayoutWidget)
self.lineEdit.setObjectName(u"lineEdit")
sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.lineEdit.sizePolicy().hasHeightForWidth())
self.lineEdit.setSizePolicy(sizePolicy)
self.gridLayout.addWidget(self.lineEdit, 0, 1, 1, 1)
self.lineEdit_2 = QLineEdit(self.gridLayoutWidget)
self.lineEdit_2.setObjectName(u"lineEdit_2")
sizePolicy.setHeightForWidth(self.lineEdit_2.sizePolicy().hasHeightForWidth())
self.lineEdit_2.setSizePolicy(sizePolicy)
self.gridLayout.addWidget(self.lineEdit_2, 1, 1, 1, 1)
self.gridLayout.setColumnStretch(1, 1)
self.retranslateUi(Dialog)
QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
Dialog.setWindowTitle(QCoreApplication.translate("Dialog", u"Dialog", None))
self.label.setText(QCoreApplication.translate("Dialog", u"TextLabel", None))
self.label_2.setText(QCoreApplication.translate("Dialog", u"TextLabel", None))
class MyMainWindow(QWidget, Ui_Dialog):
def __init__(self, *args, obj=None, **kwargs):
super().__init__(*args, **kwargs)
self.setupUi(self)
if __name__ == '__main__':
app = QApplication(sys.argv)
w = MyMainWindow()
w.show()
app.exec()
文件上说
QGridLayout获取为其提供的空间(通过其父布局或parentWidget()),...
因此,我认为问题可以归结为"如何告诉QDialog
或QMainWindow
将其所有空间都提供给一个QLayout
?
1条答案
按热度按时间q43xntqr1#
您需要在
QDialog
上设置布局,使其占据整个空间。将以下代码添加到您的Ui_Dialog()
setupUi
方法中以获得此行为。输出为: