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

Rt Rtt picture Rt Rtt · Dec 22, 2017 · Viewed 8.4k times · Source

To this question I am referring to the example calculator.py from http://zetcode.com/gui/pyqt5/layout/

In the example the QGridLayout was used. I want to ask if it is possible to define the width/height to some specific columns/rows?

Please see the picture. enter image description here E.g. I want the second column has the width of 50px and the third row has the height 80px. So that no matter how big/small the window is, these 50px, and 80px are always shown as defined. The rest rows/columns can be scaled automatically when the window size changes.

I have searched but could not find the answer.

For your convenience, I paste the code here (with tiny changes to the original version)

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

Answer

eyllanesc picture eyllanesc · Dec 22, 2017

One possible solution is to set the fixed dimensions of the widget as shown below:

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

Output:

enter image description here