如何在QGridLayout中将宽度/高度固定到特定的列/行?

6
我指的是来自http://zetcode.com/gui/pyqt5/layout/calculator.py示例中的问题。
在这个示例中,使用了QGridLayout。我想问一下是否可以将宽度/高度定义为特定的列/行?
请看图片。 enter image description here 例如,我希望第二列的宽度为50px,第三行的高度为80px。这样无论窗口大小如何,这些50px和80px始终按照定义显示。当窗口大小改变时,其余的行/列可以自动缩放。
我已经搜索过,但找不到答案。
为了方便起见,我在此处粘贴代码(与原始版本略有不同)。
# -*- coding: utf-8 -*-

import sys
from PyQt5.QtWidgets import (QWidget, QGridLayout, QPushButton, QApplication)

class Example(QWidget):
    def __init__(self):
        super(Example, self).__init__()
        self.initUI()

    def initUI(self):

        grid = QGridLayout()
        self.setLayout(grid)

        names = ['Cls', 'Bck', '', 'Close',
                 '7', '8', '9', '/',
                '4', '5', '6', '*',
                 '1', '2', '3', '-',
                '0', '.', '=', '+']

        positions = [(i,j) for i in range(5) for j in range(4)]

        for position, name in zip(positions, names):
            if name == '':
                continue
            button = QPushButton(name)
            grid.addWidget(button, *position)

        self.move(300, 150)
        self.setWindowTitle('Calculator')
        self.show()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

展示你的代码。 - eyllanesc
@eyllanesc 请查看上面的代码。我只能粘贴原始代码,因为我不知道如何为这个问题做出贡献。 - Rt Rtt
1个回答

8

一种可能的解决方案是将小部件的固定尺寸设置如下:

class Example(QWidget):
    def __init__(self):
        super(Example, self).__init__()
        self.initUI()

    def initUI(self):

        grid = QGridLayout()
        self.setLayout(grid)

        names = ['Cls', 'Bck', '', 'Close',
                 '7', '8', '9', '/',
                '4', '5', '6', '*',
                 '1', '2', '3', '-',
                '0', '.', '=', '+']

        positions = [(i,j) for i in range(5) for j in range(4)]

        for position, name in zip(positions, names):
            if name == '':
                continue
            button = QPushButton(name)
            row, column = position
            if row == 2:
                button.setFixedHeight(80)
            if column == 1:
                button.setFixedWidth(50)
            grid.addWidget(button, *position)

        self.move(300, 150)
        self.setWindowTitle('Calculator')
        self.show()

输出:

在此输入图像描述


这段内容涉及IT技术,展示了一个图片链接。

谢谢你的帮助!这确实是一个好方法。但我实际上想要一个更通用的解决方案。在某些情况下,不仅仅是简单的按钮,而是更复杂的布局/小部件放置在QGridLayout中。 - Rt Rtt
很遗憾,目前没有通用解决方案。 - eyllanesc

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接