Python PyQt5 QHBoxLayout 水平佈局用法與範例

本篇 ShengYu 介紹 Python PyQt5 QHBoxLayout 水平佈局用法與範例,QHBoxLayout 能讓 UI 元件橫向/水平/左右的方式排列,相較於手動排版 QHBoxLayout 能夠讓開發者很快速方便地讓元件佈局。

以下的 Python PyQt5 QHBoxLayout 用法與範例將分為這幾部分,

  • PyQt5 QHBoxLayout 基本用法
  • PyQt5 QHBoxLayout 放入不同元件

PyQt5 QHBoxLayout 基本用法

這邊示範 PyQt5 QHBoxLayout 基本用法,這邊示範將三個按鈕放入一個 QHBoxLayout 垂直佈局上,

python-pyqt-qvboxlayout.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
from PyQt5.QtWidgets import (QApplication, QWidget, QHBoxLayout, QPushButton)

class MyWidget(QWidget):
def __init__(self):
super().__init__()
self.initUI()

def initUI(self):
self.setWindowTitle('my window')
self.setGeometry(50, 50, 200, 150)

layout = QHBoxLayout()
self.setLayout(layout)

self.mybutton1 = QPushButton('button 1', self)
layout.addWidget(self.mybutton1)

self.mybutton2 = QPushButton('button 2', self)
layout.addWidget(self.mybutton2)

self.mybutton3 = QPushButton('button 3', self)
layout.addWidget(self.mybutton3)

if __name__ == '__main__':
app = QApplication(sys.argv)
w = MyWidget()
w.show()
sys.exit(app.exec_())

結果圖如下,

PyQt5 QHBoxLayout 放入不同元件

這邊示範將不同的 UI 元件放入一個 QHBoxLayout 水平佈局上,分別是一個 label、一個 lineEdit 與一個 button 按鈕,

python-pyqt-qvboxlayout2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
from PyQt5.QtWidgets import (QApplication, QWidget, QHBoxLayout,
QLabel, QLineEdit, QPushButton)

class MyWidget(QWidget):
def __init__(self):
super().__init__()
self.initUI()

def initUI(self):
self.setWindowTitle('my window')
self.setGeometry(50, 50, 200, 150)

layout = QHBoxLayout()
self.setLayout(layout)

self.mylabel = QLabel('username:', self)
layout.addWidget(self.mylabel)

self.mylineedit = QLineEdit(self)
layout.addWidget(self.mylineedit)

self.mybutton = QPushButton('Login', self)
layout.addWidget(self.mybutton)

if __name__ == '__main__':
app = QApplication(sys.argv)
w = MyWidget()
w.show()
sys.exit(app.exec_())

結果圖如下,

以上就是 Python PyQt5 QHBoxLayout 水平佈局用法與範例介紹,
如果你覺得我的文章寫得不錯、對你有幫助的話記得 Facebook 按讚支持一下!

其它相關文章推薦
Python 新手入門教學懶人包
Python PyQt5 新手入門教學