Chris Aung
Chris Aung

Reputation: 9492

PyQt - Centering Widget in resizable GridLayout

My idea is to display a password entry box in the QtGui MainWindow. After the password check is being performed, it will invoke the program to display the remaining buttons. I want my password entry box to be something like this

enter image description here

this is my code:

class MainWindow(QtGui.QMainWindow):

    def __init__(self,parent = None):
        super(MainWindow,self).__init__(parent)

        self.CheckPassword()

    def CheckPassword(self):
        username_label = QtGui.QLabel("Username :")
        password_label = QtGui.QLabel("Password :")
        _username = QtGui.QLineEdit()
        _password = QtGui.QLineEdit()

        password_layout = QtGui.QGridLayout()
        password_layout.addWidget(username_label,1,0)
        password_layout.addWidget(password_label,2,0)
        password_layout.addWidget(_username,1,1)
        password_layout.addWidget(_password,2,1)

        password_widget = QtGui.QWidget()
        password_widget.setLayout(password_layout)
        self.setCentralWidget(password_widget)

My problem is, since i set the widget to become centralwidget it expand as big as the window.

So I tried to set use setMaximumSize but in that case, i can't seem to position the widget at the center of the MainWindow.

How do i set the size of the QWidget for my password entry and Position it to always center no matter what size the main window is?

Upvotes: 2

Views: 7480

Answers (2)

MadeOfAir
MadeOfAir

Reputation: 3163

This is a typical usage scenario for QFormLayout. you shouldn't use a grid layout for that.

Upvotes: 0

Viktor Kerkez
Viktor Kerkez

Reputation: 46566

You can accomplish this by setting the row and column stretch. Move the widgets to a center of the grid leaving one row and one column on both sides and then set the stretch factor for those columns.

Visual example of the grid

+------------------------------+
|   s        stretch        s  |
|   t   +-------+-------+   t  |
|   r   | label | input |   r  |
|   e   +-------+-------+   e  |
|   t   | label | input |   t  |
|   c   +-------+-------+   c  |
|   h        stretch        h  |
+------------------------------+

Code:

password_layout = QtGui.QGridLayout()
# Set the stretch
password_layout.setColumnStretch(0, 1)
password_layout.setColumnStretch(3, 1)
password_layout.setRowStretch(0, 1)
password_layout.setRowStretch(3, 1)
# Add widgets
password_layout.addWidget(username_label, 1, 1)
password_layout.addWidget(password_label, 2, 1)
password_layout.addWidget(_username, 1, 2)
password_layout.addWidget(_password, 2, 2)

Upvotes: 9

Related Questions