PyQt5教程——布局管理(4)


PyQt5中的布局管理

布局管理是GUI編程中的一個重要方面。布局管理是一種如何在應用窗口上防止組件的一種方法。我們可以通過兩種基礎方式來管理布局。我們可以使用絕對定位和布局類。

絕對定位

程序指定了組件的位置並且每個組件的大小用像素作為單位來丈量。當你使用了絕對定位,我們需要知道下面的幾點限制:

  • 如果我們改變了窗口大小,組件的位置和大小並不會發生改變。
  • 在不同平台上,應用的外觀可能不同
  • 改變我們應用中的字體的話可能會把應用弄得一團糟。
  • 如果我們決定改變我們的布局,我們必須完全重寫我們的布局,這樣非常乏味和浪費時間。

下面的例子中,使用了絕對坐標來定位組件

#!/usr/bin/python3
# -*- coding: utf-8 -*-

"""
ZetCode PyQt5 tutorial 

This example shows three labels on a window
using absolute positioning. 

author: Jan Bodnar
website: zetcode.com 
last edited: January 2015
"""

import sys
from PyQt5.QtWidgets import QWidget, QLabel, QApplication


class Example(QWidget):
    
    def __init__(self):
        super().__init__()
        
        self.initUI()
        
        
    def initUI(self):
        
        lbl1 = QLabel('Zetcode', self)
        lbl1.move(15, 10)

        lbl2 = QLabel('tutorials', self)
        lbl2.move(35, 40)
        
        lbl3 = QLabel('for programmers', self)
        lbl3.move(55, 70)        
        
        self.setGeometry(300, 300, 250, 150)
        self.setWindowTitle('Absolute')    
        self.show()
        
        
if __name__ == '__main__':
    
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

  

我們使用move()方法來定位我們的組件。在上面的例子中我們使用move()方法定位了一些標簽組件。在使用move()方法時,我們給move()方法提供了x和y坐標作為參數。move()使用的坐標系統是從左上角開始計算的。x值從左到右增長。y值從上到下增長。

lbl1 = QLabel('Zetcode', self)
lbl1.move(15, 10)

  

將標簽組件定位在x=15,y=10的坐標位置。

Absolute positioningFigure: Absolute positioning

箱布局

布局管理器的布局管理類非常靈活,實用。它是將組件定位在窗口上的首選方式。QHBoxLayout和QVBoxLayout是兩個基礎布局管理類,他們水平或垂直的線性排列組件。想象一下我們需要在右下角排列兩個按鈕。為了使用箱布局,我們將使用一個水平箱布局和垂直箱布局來實現。同樣為了使用一些必要的空白,我們將添加一些拉伸因子。

#!/usr/bin/python3
# -*- coding: utf-8 -*-

"""
ZetCode PyQt5 tutorial 

In this example, we position two push
buttons in the bottom-right corner 
of the window. 

author: Jan Bodnar
website: zetcode.com 
last edited: January 2015
"""

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()
        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_())

  

例子在右下角放置了兩個按鈕。當我們改變應用窗口大小時,它們會相對於應用窗口不改變位置。在這個例子中我們使用了QHBoxLayout和QVBoxLayout兩個布局類。

okButton = QPushButton("OK")
cancelButton = QPushButton("Cancel")

  

在這里我們創建了兩個按鈕。

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

  

這里我們創建了一個水平箱布局,並且增加了一個拉伸因子和兩個按鈕。拉伸因子在兩個按鈕之前增加了一個可伸縮空間。這會將按鈕推到窗口的右邊。

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

  

為了創建必要的布局,我們把水平布局放置在垂直布局內。拉伸因子將把包含兩個按鈕的水平箱布局推到窗口的底邊。

self.setLayout(vbox)

  

最后,我們設置一下窗口的主布局。

ButtonsFigure: Buttons

網格布局

最常用的布局類是網格布局。這個布局使用行了列分割空間。要創建一個網格布局,我們需要使用QGridLayout類。

#!/usr/bin/python3
# -*- coding: utf-8 -*-

"""
ZetCode PyQt5 tutorial 

In this example, we create a skeleton
of a calculator using a QGridLayout.

author: Jan Bodnar
website: zetcode.com 
last edited: January 2015
"""

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


class Example(QWidget):
    
    def __init__(self):
        super().__init__()
        
        self.initUI()
        
        
    def initUI(self):
        
        grid = QGridLayout()
        self.setLayout(grid)
 
        names = ['Cls', 'Bck', '', 'Close',
                 '7', '8', '9', '/',
                '4', '5', '6', '*',
                 '1', '2', '3', '-',
                '0', '.', '=', '+']
        
        positions = [(i,j) for i in range(5) for j in range(4)]
        
        for position, name in zip(positions, names):
            
            if name == '':
                continue
            button = QPushButton(name)
            grid.addWidget(button, *position)
            
        self.move(300, 150)
        self.setWindowTitle('Calculator')
        self.show()
        
        
if __name__ == '__main__':
    
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

  

在我們的例子中,我們創建了一個全是按鈕的網格布局。

grid = QGridLayout()
self.setLayout(grid)

實例化QGridLayout類,並且把這個類設為應用窗口的布局。

names = ['Cls', 'Bck', '', 'Close',
            '7', '8', '9', '/',
        '4', '5', '6', '*',
            '1', '2', '3', '-',
        '0', '.', '=', '+']

這些標簽會在之后的按鈕中使用。

positions = [(i,j) for i in range(5) for j in range(4)]

我們創建了一個網格的定位列表。

for position, name in zip(positions, names):
    
    if name == '':
        continue
    button = QPushButton(name)
    grid.addWidget(button, *position)

創建出按鈕組件,並使用addWidget()方法向布局中添加按鈕。

Calculator skeletonFigure: Calculator skeleton

文本審閱窗口示例

在網格中,組件可以跨多列或多行。在這個例子中,我們對它進行一下說明。

#!/usr/bin/python3
# -*- coding: utf-8 -*-

"""
ZetCode PyQt5 tutorial 

In this example, we create a bit
more complicated window layout using
the QGridLayout manager. 

author: Jan Bodnar
website: zetcode.com 
last edited: January 2015
"""

import sys
from PyQt5.QtWidgets import (QWidget, QLabel, QLineEdit, 
    QTextEdit, QGridLayout, QApplication)


class Example(QWidget):
    
    def __init__(self):
        super().__init__()
        
        self.initUI()
        
        
    def initUI(self):
        
        title = QLabel('Title')
        author = QLabel('Author')
        review = QLabel('Review')

        titleEdit = QLineEdit()
        authorEdit = QLineEdit()
        reviewEdit = QTextEdit()

        grid = QGridLayout()
        grid.setSpacing(10)

        grid.addWidget(title, 1, 0)
        grid.addWidget(titleEdit, 1, 1)

        grid.addWidget(author, 2, 0)
        grid.addWidget(authorEdit, 2, 1)

        grid.addWidget(review, 3, 0)
        grid.addWidget(reviewEdit, 3, 1, 5, 1)
        
        self.setLayout(grid) 
        
        self.setGeometry(300, 300, 350, 300)
        self.setWindowTitle('Review')    
        self.show()
        
        
if __name__ == '__main__':
    
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

我們創建了包含三個標簽,兩個單行編輯框和一個文本編輯框組件的窗口。布局使用了QGridLayout布局。

grid = QGridLayout()
grid.setSpacing(10)

我們創建了一個網格布局並且設置了組件之間的間距。

grid.addWidget(reviewEdit, 3, 1, 5, 1)

如果我們向網格布局中增加一個組件,我們可以提供組件的跨行和跨列參數。在這個例子中,我們讓reviewEdit組件跨了5行。

Review exampleFigure: Review example

這部分的PyQt5教程專門用於講述布局管理。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM