1

This is a really simple question I'm just new to PyQt5 and am a bit confused on how QGridLayout works...

def init_main_page(self):
        layout = QGridLayout()

        b1 = buttons.QPushButton("0",self.main_page)
        b2 = buttons.QPushButton("1",self.main_page)
        b3 = buttons.QPushButton("2",self.main_page)

        layout.addWidget(b1,0,0)
        layout.addWidget(b2,5,0)
        layout.addWidget(b3,1,0)

        self.main_page.setLayout(layout)

The problem I am having is that no matter how high I make the x and y arguments in addwidget(QWidget,x,y), it b1 b2 and b3 always remain equidistant from each other. I'm trying figure out how to manipulate the position of the buttons whilst maintaining a proportional setup (so avoiding QPushButton.move()) and from what I've seen, QGridLayout is the best way to do this.

Henrique Lee
  • 59
  • 1
  • 1
  • 7

1 Answers1

0

Setting the coordinates of widgets in a grid layout by "skipping" rows or columns is almost useless, as those are grid coordinates that only tell the layout manager in which "slots" the widgets will be: since there is nothing in the rows 2 to 4, that space will not be used.

To achieve what you want you need to set stretch factors and, possibly, use minimum heights for the specified rows.

    layout.addWidget(b1, 0, 0)
    layout.addWidget(b3, 1, 0)
    layout.addWidget(b2, 2, 0)
    layout.setRowStretch(2, 1)
    layout.setRowMinimumHeight(2, 50)

But this might not be what you want, since it will place the third button in the vertical center of the row grid (leaving empty space at the bottom).

To avoid that there are two possible solutions:

  • add the widget by setting the alignment to the bottom:

    layout.addWidget(b2, 2, 0, alignment=QtCore.Qt.AlignBottom)
    
  • add the last widget to the fourth row, and set stretch and minimum height for the third empty row.

        layout.addWidget(b2, 3, 0)
        layout.setRowStretch(2, 1)
        layout.setRowMinimumHeight(2, 50)
musicamante
  • 41,230
  • 6
  • 33
  • 58
  • I had no idea thank you so much I was able to get it to work! Is there anything wrong that I should know with having empty rows such as the third row in the last possible solution? – Henrique Lee Jun 18 '20 at 07:32
  • There is nothing wrong in "skipping" rows or columns, but sometimes you might prefer to use spacers (which is the most common approach when building an UI in Designer): you either use a [QSpacerItem](https://doc.qt.io/qt-5/qspaceritem.html) or a basic QWidget with the proper minimum and/or maximum size and correct size policy. – musicamante Jun 18 '20 at 12:34