• 布局管理——盒式布局


    QHBoxLayout和QVBoxLayout分别是水平和垂直对齐控件的基本布局类

    试想一下,我们希望把两个按钮在程序的右下角。

    • 要创建这样一个布局,我们可以使用一横一纵两个框。
    • 要创造必要的空余空间,我们可以添加一个拉伸因子(stretch factor)。

    示例效果如下:

     1 #!/usr/bin/python3
     2 # -*- coding: utf-8 -*-
     3 
     4 """
     5 ZetCode PyQt5 tutorial
     6 
     7 In this example, we position two push
     8 buttons in the bottom-right corner
     9 of the window.
    10 
    11 Author: Jan Bodnar
    12 Website: zetcode.com
    13 Last edited: August 2017
    14 """
    15 
    16 import sys
    17 from PyQt5.QtWidgets import (QWidget, QPushButton,
    18     QHBoxLayout, QVBoxLayout, QApplication)
    19 
    20 
    21 class Example(QWidget):
    22 
    23     def __init__(self):
    24         super().__init__()
    25 
    26         self.initUI()
    27 
    28 
    29     def initUI(self):
    30 
    31         # create two push buttons
    32         okButton = QPushButton("OK")
    33         cancelButton = QPushButton("Cancel")
    34 
    35         hbox = QHBoxLayout()
    36         hbox.addStretch(1)
    37         hbox.addWidget(okButton)
    38         hbox.addWidget(cancelButton)
    39 
    40         vbox = QVBoxLayout()
    41         vbox.addStretch(1)
    42         vbox.addLayout(hbox)
    43 
    44         self.setLayout(vbox)
    45 
    46         self.setGeometry(300, 300, 300, 150)
    47         self.setWindowTitle('Buttons')
    48         self.show()
    49 
    50 
    51 if __name__ == '__main__':
    52 
    53     app = QApplication(sys.argv)
    54     ex = Example()
    55     sys.exit(app.exec_())

    这个例子在窗口的右下角放置了两个按钮。当我们调整应用程序窗口的大小时,他们是固定在右下角的。我们同时使用HBoxLayout 和QVBoxLayout布局。

    hbox = QHBoxLayout()
    hbox.addStretch(1)
    hbox.addWidget(okButton)
    hbox.addWidget(cancelButton)

    我们创建了一个水平box布局,添加了拉伸因子(addStretch),添加(addWidget)两个按钮。在添加两个按钮之前增加了一个拉伸因子,这可以将两个按钮推到窗口右侧。

    vbox = QVBoxLayout()
            vbox.addStretch(1)
            vbox.addLayout(hbox)

    要得到我们想要的布局,还需将横向布局放入垂直的布局中。在垂直框上的拉伸因子会将水平框包括里面的控件推至窗口的底部。

    self.setLayout(vbox)

    最后,我们设置窗口的主布局。

  • 相关阅读:
    【学习总结】Git学习-参考廖雪峰老师教程二-安装Git
    【学习总结】Git学习-参考廖雪峰老师教程一-Git简介
    【学习总结】vi/vim命令是使用
    【学习总结】Git学习-参考廖雪峰老师教程-总
    【kindle笔记】之 《鬼吹灯》-9-20
    【学习总结】win7下安装Ubuntu双系统的日常
    【kindle笔记】之 《明朝那些事儿》-2018-7-1
    【kindle笔记】之 《黑客微百科》-2018-6-17
    【kindle笔记】之 《恶意》-2018-4-20
    【kindle笔记】之 《活着》-2018-2-5
  • 原文地址:https://www.cnblogs.com/fuqia/p/8733338.html
Copyright © 2020-2023  润新知