PyQt5:如何在QGridLayout中修改特定列/行的宽度/高度?

时间:2017-12-22 15:13:27

标签: python pyqt pyqt5

对于这个问题,我指的是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_())

1 个答案:

答案 0 :(得分:2)

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

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

输出:

enter image description here