PyQt布局之【QHBoxLayout、QVBoxLayout——表单布局】

欢迎加入QQ群:853840665,一块学习讨论

QHBoxLayout和QVBoxLayout是基本的布局类,它可以水平和垂直地排列小部件。

方法如下:

Sr.No. Methods & Description
1

addWidget()

Add a widget to the BoxLayout

2

addStretch()

Creates empty stretchable box

3

addLayout()

Add another nested layout

我们现在通过在一个窗口的右下角放两个按键来学习这两个布局

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


class Example(QWidget):
    
    def __init__(self):
        super().__init__()
        
        self.initUI()
           
    def initUI(self):
        #创建两个按键
        okButton = QPushButton("OK")
        cancelButton = QPushButton("Cancel")
        #创建一个水平布局
        hbox = QHBoxLayout()
        #伸缩量设置为1
        hbox.addStretch(1)
        hbox.addWidget(okButton)
        hbox.addWidget(cancelButton)

        self.setLayout(hbox)
        
        self.setGeometry(300, 300, 300, 150)
        self.setWindowTitle('Buttons')    
        self.show()        
        
if __name__ == '__main__':
    
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

运行效果如下

代码分析:

 hbox.addStretch(1)

我们在创建一个水平布局后,由于添加控件是从左往右自动排序的(这个可以通过setLayoutDirection(Qt.RightToLeft)方法更改),所以在首先添加一个伸缩量之后,这个伸缩量占满了左边的剩余空间。addStretch(1)中的参数是比例的意思,但是这里我们在水平方向只添加了一个伸缩量,所以不管这里的值是多少,它都会占满这里的剩余空间。

下面再添加一个Strech,参数哪怕设置为0,我们可以看到运行结果依然是两个Strech平分剩余空间(0:0)

       hbox.addStretch(0)
       hbox.addWidget(okButton)
       hbox.addStretch(0)
       hbox.addWidget(cancelButton)

hbox.addStretch(1)
hbox.addWidget(okButton)
hbox.addStretch(0)
hbox.addWidget(cancelButton)

但是如果前者为1,后者为0,那么后者是不起作用的,效果如下

我想现在大家对Strech和水平布局应该有个感性的认识了,那么怎么把这个水平布局放在右下方呢?

这里是新建一个垂直方向的子布局,把上面这个水平方向布局添加到垂直布局下面,代码如下

import sys
from PyQt5.QtWidgets import (QWidget, QPushButton, 
    QHBoxLayout, QVBoxLayout, QApplication)
from PyQt5.QtCore import Qt


class Example(QWidget):
    
    def __init__(self):
        super().__init__()
        
        self.initUI()
           
    def initUI(self):
        #创建两个按键
        okButton = QPushButton("OK")
        cancelButton = QPushButton("Cancel")
        #创建一个水平布局
        hbox = QHBoxLayout()
        #伸缩量设置为1
        hbox.addStretch(1)
        hbox.addWidget(okButton)
        hbox.addWidget(cancelButton)

        #新建一个垂直布局
        vbox = QVBoxLayout()
        #垂直布局的默认摆放是从上往下,这里添加一个伸缩量占满上方的剩余空间,那么上面两个按键所在的布局就会往下跑
        vbox.addStretch(1)
        #把水平布局添加到垂直布局
        vbox.addLayout(hbox)
  
        self.setLayout(vbox)
        self.setGeometry(300, 300, 300, 150)
        self.setWindowTitle('Buttons')    
        self.show()        
        
if __name__ == '__main__':
    
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

效果如下

猜你喜欢

转载自blog.csdn.net/jxwzh/article/details/81480621