PyQt5 - Unable to get QPushButton to size properly in a QGridLayout

33 views Asked by At

I wanted to get insight into widget resizing behavior I noticed, and it may have to do with wanting to create a set of push buttons in a grid. Here is a snippet:

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

class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setGeometry(10, 10, 780, 460)
        self.setWindowTitle("Frame with Grid")

        self.gLayout = QGridLayout()
        self.setLayout(self.gLayout)

        # Populate some data in grid cells
        row = 0
        for col in range(5):
            pb = QPushButton(str(row) + ", " + str(col))
            #pb.resize(50, 50)
            styleStr = "QPushButton { padding-right: 20px; padding-left: 20px; }"
            pb.setStyleSheet(styleStr)
            self.gLayout.addWidget(pb, row, col)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec())

The example creates the set of buttons, but I cannot get the padding on right and left to work as I expect.

I also tried explicitly resizing the PushButton but that too does not have the expected effect. My assumption is that I am doing something wrong, so any guidance would be greatly appreciated.

0

There are 0 answers