如果需要在水平布局中使用非等尺寸的子项,可以使用QGridLayout作为替代方案。下面是一个使用QGridLayout的示例代码:
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QGridLayout, QLabel, QPushButton
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
grid = QGridLayout()
self.setLayout(grid)
# 创建子项
label1 = QLabel('Label 1', self)
button1 = QPushButton('Button 1', self)
label2 = QLabel('Label 2', self)
button2 = QPushButton('Button 2', self)
# 设置子项所在的行和列
grid.addWidget(label1, 0, 0) # 第一个参数是子项,第二个参数是行索引,第三个参数是列索引
grid.addWidget(button1, 0, 1)
grid.addWidget(label2, 1, 0)
grid.addWidget(button2, 1, 1)
self.setGeometry(300, 300, 300, 200)
self.setWindowTitle('QGridLayout Example')
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
在上面的示例中,我们使用QGridLayout替代了QHBoxLayout,并且可以灵活地设置每个子项的行和列,从而实现了非等尺寸的布局。