盒布局
from PyQt5.QtWidgets import QWidget, QPushButton
from PyQt5.QtWidgets import QHBoxLayout, QVBoxLayout
class myWidget(QWidget):
def __init__(self):
super().__init__()
self.init_ui()
def init_ui(self):
okbtn = QPushButton("确认")
cancelbtn = QPushButton("取消")
hbox = QHBoxLayout()
hbox.addStretch(1)
hbox.addWidget(okbtn)
hbox.addWidget(cancelbtn)
vbox = QVBoxLayout()
vbox.addStretch(1)
vbox.addLayout(hbox)
self.setLayout(vbox)
self.setGeometry(300, 300, 250, 150)
self.setWindowTitle("按键")
self.show()
栅格布局
from PyQt5.QtWidgets import QWidget, QGridLayout
from PyQt5.QtWidgets import QPushButton
class myWidget(QWidget):
def __init__(self):
super().__init__()
self.init_ui()
def init_ui(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
btn = QPushButton(name)
grid.addWidget(btn, *position)
self.move(300, 150)
self.setWindowTitle("栅格布局")
self.show()
例子:制作反馈窗口
from PyQt5.QtWidgets import QWidget, QLabel, QLineEdit
from PyQt5.QtWidgets import QTextEdit, QGridLayout
class myWidget(QWidget):
def __init__(self):
super().__init__()
self.init_ui()
def init_ui(self):
title = QLabel("标题")
author = QLabel("作者")
review = QLabel("回复")
titleEdit = QLineEdit()
authorEdit = QLineEdit()
reviewEdit = QLineEdit()
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)
self.setLayout(grid)
self.move(300, 300)
self.setWindowTitle("回复窗口")
self.show()
from PyQt5.QtWidgets import QWidget, QLabel, QLineEdit, QPushButton
from PyQt5.QtWidgets import QTextEdit, QGridLayout, QHBoxLayout, QVBoxLayout
class myWidget(QWidget):
def __init__(self):
super().__init__()
self.init_ui()
def init_ui(self):
title = QLabel("标题")
author = QLabel("作者")
review = QLabel("回复")
titleEdit = QLineEdit()
authorEdit = QLineEdit()
reviewEdit = QLineEdit()
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)
okbtn = QPushButton("确定")
concelbtn = QPushButton("取消")
hbox = QHBoxLayout()
hbox.addStretch(1)
hbox.addWidget(okbtn)
hbox.addWidget(concelbtn)
vbox = QVBoxLayout()
vbox.addStretch(1)
vbox.addLayout(grid)
vbox.addLayout(hbox)
self.setLayout(vbox)
self.move(300, 300)
self.setWindowTitle("回复窗口")
self.show()