水平布局:
代码:
# -*- coding: utf-8 -*-
import sys
from PyQt5.QtWidgets import *
class WinForm(QWidget):
def __init__(self, parent = None):
super(WinForm,self).__init__(parent)
self.setWindowTitle('水平布局管理例子')
hlayout = QHBoxLayout()
hlayout.addWidget(QPushButton(str(1)))
hlayout.addWidget(QPushButton(str(2)))
hlayout.addWidget(QPushButton(str(3)))
hlayout.addWidget(QPushButton(str(4)))
hlayout.addWidget(QPushButton(str(5)))
hlayout.addWidget(QPushButton(str(6)))
self.setLayout(hlayout)
if __name__ == "__main__":
app = QApplication(sys.argv)
form = WinForm()
form.show()
sys.exit(app.exec_())
竖直布局与这个差不多就把QHBoxLayout 改成 QVBoxLayout 就可以啦。
addStretch函数:
# -*- coding: utf-8 -*-
import sys
from PyQt5.QtWidgets import *
class WinForm(QWidget):
def __init__(self, parent = None):
super(WinForm,self).__init__(parent)
self.setWindowTitle('伸缩量管理例子')
btn1 = QPushButton()
btn2 = QPushButton()
btn3 = QPushButton()
btn1.setText('one')
btn2.setText('two')
btn3.setText('three')
hbox = QHBoxLayout()
hbox.addStretch(2)
hbox.addWidget(btn1)
hbox.addStretch(2)
hbox.addWidget(btn2)
hbox.addStretch(2)
hbox.addWidget(btn3)
self.setLayout(hbox)
if __name__ == "__main__":
app = QApplication(sys.argv)
form = WinForm()
form.show()
sys.exit(app.exec_())
QGridLayout
常用的方法:
代码:
# -*- coding: utf-8 -*-
import sys
from PyQt5.QtWidgets import *
class FormW(QWidget):
def __init__(self,parent = None):
super(FormW,self).__init__(parent)
self.initUI()
def initUI(self):
#1
grid = QGridLayout()
self.setLayout(grid)
#2
names =['Cls', 'Back', '', 'Close',
'7', '8','9','/',
'4','5','6','*',
'1','2','3','-',
'0','.','=','+']
#3
positions = [(i,j) for i in range(5) for j in range(4)]
#4
for position, name in zip(positions,names):
if name == '':
continue
button = QPushButton(name)
grid.addWidget(button,*position)
self.move(300,150)
self.setWindowTitle('网络布局管理例子')
if __name__ == "__main__":
app = QApplication(sys.argv)
form = FormW()
form.show()
sys.exit(app.exec_())
基本布局就简单介绍到这里,如果想比较复杂的话,请使用他们相互的组合。这个还是非常简单的。