简体   繁体   English

如何在 PyQt5 中为 QGridLayout 添加拉伸?

[英]How to add stretch for QGridLayout in PyQt5?

I created widgets in a grid-layout.我在网格布局中创建了小部件。 The widgets are stretching based on the window.小部件根据窗口进行拉伸。 Is it possible to avoid the stretching and align them as shown in picture below?是否可以避免拉伸并将它们对齐,如下图所示? I created a code to achieve this, but I feel it is not a straightforward solution.我创建了一个代码来实现这一点,但我觉得这不是一个简单的解决方案。 If there are any better solutions to achieve this, please share them.如果有更好的解决方案来实现这一点,请分享它们。

Grid layout result:网格布局结果:

from PyQt5.QtWidgets import *
app =QApplication([])
window=QWidget()
GL=QGridLayout(window)
GL.addWidget(QPushButton('R1C1'),0,0)
GL.addWidget(QPushButton('R1C2'),0,1)
GL.addWidget(QPushButton('R2C1'),1,0)
GL.addWidget(QPushButton('R1C1'),1,1)
window.showMaximized()
app.exec_()

在此处输入图片说明

Required Result:要求的结果:

在此处输入图片说明

My code:我的代码:

from PyQt5.QtWidgets import *
app =QApplication([])
window=QWidget()
VL=QVBoxLayout(window);HL=QHBoxLayout();VL.addLayout(HL)
GL=QGridLayout();HL.addLayout(GL)
GL.addWidget(QPushButton('R1C1'),0,0)
GL.addWidget(QPushButton('R1C2'),0,1)
GL.addWidget(QPushButton('R2C1'),1,0)
GL.addWidget(QPushButton('R1C1'),1,1)
HL.addStretch();VL.addStretch()
window.showMaximized()
app.exec_()

The QGridLaout class doesn't have any simple convenience methods like QBoxLayout.addStretch() for achieving this. QGridLaout类没有像QBoxLayout.addStretch()这样的简单方便的方法来实现这一点。 But the same effect can be achieved by adding some empty, stretchable rows/columns, like this:但是可以通过添加一些空的、可拉伸的行/列来实现相同的效果,如下所示:

GL.setRowStretch(GL.rowCount(), 1)
GL.setColumnStretch(GL.columnCount(), 1)

截屏

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM