如何在 QGridLayout 中将 width/height 修复为特定的 column/row?

How to fix the width/height to specific column/row in QGridLayout?

关于这个问题,我指的是来自 http://zetcode.com/gui/pyqt5/layout/

的示例 calculator.py

示例中使用了 QGridLayout。我想问一下是否可以将 width/height 定义为某些特定的 columns/rows?

请看图片。 例如。我希望第二列的宽度为 50px,第三行的高度为 80px。这样无论big/small和window如何,这50px和80px总是按定义显示。其余rows/columns可以在window大小变化时自动缩放。

我已经搜索过但找不到答案。

为了您的方便,我把代码贴在这里(对原始版本有微小的改动)

# -*- 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_())

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

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()

输出: