简体   繁体   English

PyQt - 在可调整大小的GridLayout中居中小部件

[英]PyQt - Centering Widget in resizable GridLayout

My idea is to display a password entry box in the QtGui MainWindow . 我的想法是在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 我希望我的密码输入框是这样的

在此输入图像描述

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. 我的问题是,因为我将小部件设置为centralwidget它扩展到窗口大。

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 . 所以我试图设置使用setMaximumSize但是在那种情况下,我似乎无法将小部件放置在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? 无论主窗口的大小如何,我如何为密码输入设置QWidget的大小并将其定位为始终居中?

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)

This is a typical usage scenario for QFormLayout . 这是QFormLayout的典型使用方案。 you shouldn't use a grid layout for that. 您不应该为此使用网格布局。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM