PyQt5, BoxLayout

王磊的程序员之路 2019-06-28

PyQt5, BoxLayout

BoxLayout简介

盒子布局类似于网格布局, 但是它仅支持单行或一列小部件,具体取决于方向,但它会动态调整其包含的数量或部件的大小。

创建

boxlayout = QBoxLayout()

方法

使用以方法将小部件插入到BoxLayout中:

boxlayout.addWidget(widget, stretch, alignment)
boxlayout.insertWidget(index, widget, stretch, alignment)

insertWidget方法中的index表示应该放置子部件的位置。widget参数是添加到BoxLayout的子部件,stretch的值应该设置为一个整数,表示子部件伸缩的数值,最后,alignment的值可以设置为以下之一:

Qt.AlignmentLeft
Qt.AlignmentRight
Qt.AlignmentHCenter
Qt.AlignmentJustify

布局对象通过其它方法添加到BoxLayou中:

boxlayout.addLayout(layout, stretch)
boxlayout.insertLayout(index, layout, stretch)

每个子部件之间的像素间距默认为零,但是可以通过以下方式配置:

boxlayout.setSpacing(spacing)

间距也可以通过以下方式添加到普通窗口小部件中:

boxlayout.addSpacing(spacing)
boxlayout.indterSpacing(index, spacing)

spacing的值表示的是要显示的像素间距的数量,.instertSpacing()方法还需要一个index, 表示的是插入该间距的位置.BoxLayou的方向可以通过以下方式设置:

boxlayout.setDirection(direction)

direction参数必须设置为以下之一:

QBoxLayout.LeftToRight
QBoxLayout.RightToLeft
QBoxLayout.TopToBottom
QBoxLayout.BottomToTop

Example

# !/usr/bin/python

from PyQt5.QtWidgets import * 
import sys

    class Window(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        
        layout = QBoxLayout(QBoxLayout.LeftToRight)
        self.setLayout(layout)
        
        label = QLabel("Label 1")
        layout.addWidget(label, 0)
        label1 = QLabel("Label 2")
        layout.addWidget(label1, 0 )
        
        layout2 = QBoxLayout(QBoxLayout.TopToBottom)
        layout.addLayout(layout2)
        
        label = QLabel("Label 3")
        layout2.addWidget(label, 0)
        label = QLabel("Label 4")
        layout2.addWidget(label, 0)

app = QApplication(sys.argv)

screen = Window()
screen.show()

sys.exit(app.exec_())

相关推荐