绝对定位
import sys
from PyQt5.QtWidgets import QWidget, QApplication, QLabel
class Myform(QWidget):
def __init__(self):
super(Myform, self).__init__()
self.initUI()
def initUI(self):
l1 = QLabel('l1', self)
l1.move(0, 0)
l2 = QLabel('l2', self)
l2.move(40, 40)
l3 = QLabel('l3', self)
l3.move(80, 80)
self.setGeometry(300, 200, 200, 150)
self.setWindowTitle('absolute position')
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
w = Myform()
sys.exit(app.exec_())
盒子布局
import sys
from PyQt5.QtWidgets import QWidget, QApplication, QPushButton, QHBoxLayout, QVBoxLayout
class Myform(QWidget):
def __init__(self):
super(Myform, self).__init__()
self.initUI()
def initUI(self):
ok = QPushButton('OK')
cancel = QPushButton('Cancel')
hbox = QHBoxLayout()
hbox.addStretch(1)
hbox.addWidget(ok)
hbox.addWidget(cancel)
vbox = QVBoxLayout()
vbox.addLayout(hbox)
vbox.addStretch(1)
self.setLayout(vbox)
self.setGeometry(300, 300, 300, 200)
self.setWindowTitle('box')
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
w = Myform()
sys.exit(app.exec_())
网格布局
import sys
from PyQt5.QtWidgets import QWidget, QApplication,QPushButton, QGridLayout
class Myform(QWidget):
def __init__(self):
super(Myform, self).__init__()
self.initUI()
def initUI(self):
grid = QGridLayout()
self.setLayout(grid)
btns = ['存储', '取存', '退格', '清屏',
'累存', '积存', '清存', '/',
'7', '8', '9', '*',
'4', '5', '6', '-',
'1', '2', '3', '+',
'0', '.', '+/-', '='
]
positions = [(i, j) for i in range(6) for j in range(4)]
for position, btn in zip(positions, btns):
if btn == '':
pass
btn = QPushButton(btn)
grid.addWidget(btn, *position)
self.move(300, 300)
self.setWindowTitle('grid')
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
w = Myform()
sys.exit(app.exec_())
网格布局二
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QLineEdit, QTextEdit, QGridLayout
class Myform(QWidget):
def __init__(self):
super(Myform, self).__init__()
self.initUI()
def initUI(self):
title = QLabel('Title')
author = QLabel('Author')
article = QLabel('Article')
titleEdit = QLineEdit()
authorEdit = QLineEdit()
articleEdit = 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(article, 3, 0)
grid.addWidget(articleEdit, 3, 1, 5, 1)
self.setLayout(grid)
self.move(300, 300)
self.setWindowTitle('layout')
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
w = Myform()
sys.exit(app.exec_())