例1:绝对定位
import sys
from PyQt5.QtWidgets import QWidget, QLabel, QLineEdit, QApplication
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
lbl1 = QLabel('姓名', self)
lbl1.move(15, 15)
lbl2 = QLabel('学号', self)
lbl2.move(15, 40)
name_LineEdit = QLineEdit(self)
name_LineEdit.move(55, 15)
num_LineEdit = QLineEdit(self)
num_LineEdit.move(55, 40)
self.setGeometry(300, 300, 250, 150)
self.setWindowTitle('绝对定位')
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
ex.show()
sys.exit(app.exec_())
例2:使用水平和垂直布局
import sys
from PyQt5.QtWidgets import (QWidget, QLabel, QLineEdit, QHBoxLayout,
QVBoxLayout, QApplication)
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
lbl1 = QLabel('姓名')
lbl2 = QLabel('学号')
name_LineEdit = QLineEdit()
num_LineEdit = QLineEdit()
hBox1 = QHBoxLayout()
hBox1.addWidget(lbl1)
hBox1.addWidget(name_LineEdit)
hBox1.addStretch(1)
hBox2 = QHBoxLayout()
hBox2.addWidget(lbl2)
hBox2.addWidget(num_LineEdit)
hBox2.addStretch(2)
vBox = QVBoxLayout()
vBox.addLayout(hBox1)
vBox.addLayout(hBox2)
self.setLayout(vBox)
self.setGeometry(300, 300, 250, 150)
self.setWindowTitle('布局')
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
ex.show()
sys.exit(app.exec_())
例3:使用网格布局
import sys
from PyQt5.QtWidgets import (QWidget, QLabel, QLineEdit,
QGridLayout, QApplication)
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
lbl1 = QLabel('姓名')
lbl2 = QLabel('学号')
name_lineEdit = QLineEdit()
num_lineEdit = QLineEdit()
grid_layout = QGridLayout()
grid_layout.addWidget(lbl1, 0, 0)
grid_layout.addWidget(lbl2, 1, 0)
grid_layout.addWidget(name_lineEdit, 0, 1)
grid_layout.addWidget(num_lineEdit, 1, 1)
self.setLayout(grid_layout)
self.setGeometry(300, 300, 250, 150)
self.setWindowTitle('绝对定位')
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
ex.show()
sys.exit(app.exec_())
例4:组件能跨行跨列
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_())