Python PyQt5 I wanna set the position of my Grid Layout

Question:

I need to set the position of my Grid Layout. It has to be exactly where I want it to be. I’ve tried some methods like ".setGeometry, .setAlignment" and I couldn’t unfortunately have the result exactly I wanted. enter image description here

As you can see from this photo, I want it to be in the bottom right but I guess there’s no method for it. (I need to say that the interface in the photo below is a different interface. I don’t need this interface. Because of I wanted to show you exactly what kind of stuff I wanted.)

Asked By: Deezwend

||

Answers:

You can achieve this using layouts and their setStretch methods.

Here is a runnable example:

from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *

class MainWindow(QMainWindow):
    def __init__(self, parent=None) -> None:
        super().__init__(parent)
        self.central = QWidget()

        # create a vertical layout and add stretch so it is the first
        # item of the layout and everything that is inserted after
        # is pushed down to the bottom
        self.layout = QVBoxLayout(self.central)
        self.layout.addStretch()
       
        self.btn1 = QPushButton("PushButton", self)
        self.btn2 = QPushButton("PushButton", self)
        self.btn3 = QPushButton("PushButton", self)

        # create a horizontal layout and add stretch so everything is 
        # pushed to the right
        self.hlayout = QHBoxLayout()
        self.hlayout.addStretch()

        # add buttons after the stretch so they will be pushed to the 
        # right
        self.hlayout.addWidget(self.btn1)
        self.hlayout.addWidget(self.btn2)
        self.hlayout.addWidget(self.btn3)

        # add horizontal layout to vertical layout which will be pushed
        # to the bottom from the vertical layouts stretch
        self.layout.addLayout(self.hlayout)
        self.setCentralWidget(self.central)

app = QApplication([])
window = MainWindow()
window.show()
app.exec_()

The alternative would be to use the QHBoxLayout.setgeometry(QRect(x, y, w, h)) but this will force the layout into a specific position that will not adjust dynamically if you resize the window, or for any other reason.

This is essentially what is happening in the code above. The blue lines would represent the stretch. the stretch can be thought of as invisible pressure that can be inserted into any layout, before, after, or between any widgets, It can work in either direction.

This same process can be done using QGridWidget.

enter image description here

Answered By: Alexander
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.