PyQt5布局管理(QBoxLayout(框布局))
QBoxLayout(框布局)
采用QBoxLayout类可以在水平和垂直方向上排列控件,QHBoxLayout和
QVBoxLayout类继承自QBoxLayout类。
QHBoxLayout(水平布局)
采用QHBoxLayout类,按照从左到右的顺序来添加控件。QHBoxLayout类中的
常用方法如表6-1所示。
方法 | 描述 |
---|---|
addLayout(self,QLayout,stretch=0) | 在窗口的右边添加布局,使用stretc(伸缩量)进行伸, |
伸缩量默认为0 | |
addWidget(self,QWidget,stretch,Qt.Alignment alignment) | 在布局中添加控件:- stretch(伸缩量),只适用于QBoxLayout,控件和窗口会随着伸缩量的变大而增大- alignment,指定对齐的方式 |
addSpacing(self,int) | 设置各控件的上下间距.通过该方法可以增加额外的空间 |
QHBoxLayout类的继承结构如下: | |
在创建QHBoxLayout布局时用到的对齐方式参数如表6-2所示。 | |
参数 | 描述 |
— | — |
Qt.AlignLeft | 水平方向居左对齐 |
Qt.AlignRight | 水平方向居右对齐 |
Qt.AlignCenter | 水平方向居中对齐 |
Qt.ALignJustify | 水平万向两端对齐 |
Qt.AlignTop | 重直方向上对齐 |
Qt.AlignBottom | 垂直方向靠下对齐 |
Qt.AlignVCenter | 垂直方向居中对齐 |
import sys
from PyQt5.QtWidgets import QApplication,QWidget,QHBoxLayout,QPushButtonclass Winform(QWidget):def __init__(self,parent=None):super(Winform,self).__init__(parent)self.setWindowTitle("水平布局管理例子")#水平布局按照从左到右的顺序进行添加按钮部件hlayout = QHBoxLayout()hlayout.addWidget(QPushButton(str(1)))hlayout.addWidget(QPushButton(str(2)))hlayout.addWidget(QPushButton(str(3)))hlayout.addWidget(QPushButton(str(4)))hlayout.addWidget(QPushButton(str(5)))self.setLayout(hlayout)if __name__ == '__main__':app = QApplication(sys.argv)form = Winform()form.show()sys.exit(app.exec_())
运行结果
QVBoxLayout(垂直布局)
import sys
from PyQt5.QtWidgets import QApplication,QWidget,QVBoxLayout,QPushButtonclass Winform(QWidget):def __init__(self,parent=None):super(Winform,self).__init__(parent)self.setWindowTitle("垂直布局管理例子")self.resize(330,150)#垂直布局按照从上到下的顺序进行添加按钮部件vlayout = QVBoxLayout()vlayout.addWidget(QPushButton(str(1)))vlayout.addWidget(QPushButton(str(2)))vlayout.addWidget(QPushButton(str(3)))vlayout.addWidget(QPushButton(str(4)))vlayout.addWidget(QPushButton(str(5)))self.setLayout(vlayout)if __name__ == '__main__':app = QApplication(sys.argv)form=Winform()form.show()sys.exit(app.exec_())
运行结果
addStretch()函数的使用
在布局时要用到addStretch()函数。设置stretch伸缩量后,按比例分配剩余空间。
addStretch()函数的具体使用请参考表6-3。
函数 | 描述 |
---|---|
QBoxLayout.addStretch(int stretch=0) | addStretch()函数在布局管理器中增能一个可伸缩的控件(QSpaceItem),0 |
为最小值,并且将stretch作为伸缩量添加到布局末尾 | |
streteh参数表示均分的比例,默认值为0 |
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QPushButton
import sysclass WindowDemo(QWidget):def __init__(self):super().__init__()btn1 = QPushButton(self)btn2 = QPushButton(self)btn3 = QPushButton(self)btn1.setText('button 1')btn2.setText('button 2')btn3.setText('button 3')hbox = QHBoxLayout()# 设置伸缩量为1hbox.addStretch(1)hbox.addWidget(btn1)# 设置伸缩量为1hbox.addStretch(1)hbox.addWidget(btn2)# 设置伸缩量为1hbox.addStretch(1)hbox.addWidget(btn3)# 设置伸缩量为1hbox.addStretch(1)self.setLayout(hbox)self.setWindowTitle("addStretch 例子")if __name__ == "__main__":app = QApplication(sys.argv)win = WindowDemo()win.show()sys.exit(app.exec_())
运行结果