Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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_())
like image 228
Rt Rtt Avatar asked Dec 22 '17 15:12

Rt Rtt


1 Answers

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

like image 151
eyllanesc Avatar answered Oct 06 '22 22:10

eyllanesc