目录
本系列文章前情回顾:
设计好的button、lineEdit等等工具,就需要将这些在洁面上进行排布,就需要Box布局、网格Grid布局
1.BoxLayout水平/垂直布局
http://www.mamicode.com/info-detail-1251502.html
__author__ = "lingjun"
# 公众号:小白CV
# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtCore
from PyQt4 import QtGui
QtCore.QTextCodec.setCodecForTr(QtCore.QTextCodec.codecForName("utf8"))
class BoxLayout(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self)
self.setWindowTitle(u'Box布局')
# 设定按钮
ok=QtGui.QPushButton(u'确定')
cancel = QtGui.QPushButton(u'取消')
# 水平布局
hbox = QtGui.QHBoxLayout()
hbox.addStretch(1) # 添加伸缩间隔元素,创建必须的空白空间
hbox.addWidget(ok)
hbox.addWidget(cancel)
# 垂直布局
vbox = QtGui.QVBoxLayout()
vbox.addStretch(1)
vbox.addLayout(hbox) # 把水平布局放在垂直布局里面
self.setLayout(vbox) # 设置窗口的主布局
self.resize(400, 250)
if __name__ == "__main__":
app=QtGui.QApplication(sys.argv)
b=BoxLayout()
b.show()
app.exec_()
2.GridLayout网格布局,设计计算器
class GridLayout(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self)
self.setWindowTitle(u'Grid计算器网格布局')
names=[u'清除', u'后退',"", u'关闭',
'7', '8', '9', '/',
'4', '5', '6', '*',
'1', '2', '3', '-',
'0', '.', '=', '+']
grid = QtGui.QGridLayout()
j = 0
pos = [(0,0), (0,1), (0,2), (0,3),
(1,0), (1,1), (1,2), (1,3),
(2,0), (2,1), (2,2), (2,3),
(3,0), (3,1), (3,2), (3,3),
(4,0), (4,1), (4,2), (4,3)]
for i in names:
button = QtGui.QPushButton(i)
if j == 2:
grid.addWidget(QtGui.QLabel(''), 0, 2)
else:
grid.addWidget(button, pos[j][0], pos[j][1])
j += 1
self.setLayout(grid) # 设置窗口的主布局
if __name__ == "__main__":
app=QtGui.QApplication(sys.argv)
b=GridLayout()
b.show()
app.exec_()
如果你和我一样有点粗心,可能就出现下面的结果了,是一个“”空格惹的祸
最后经过仔细的观察,发现是这样的
小白CV:公众号旨在专注CV(计算机视觉)、AI(人工智能)领域相关技术,文章内容主要围绕C++、Python编程技术,机器学习(ML)、深度学习(DL)、OpenCV等图像处理技术,深度发掘技术要点,记录学习工作中常用的操作,做你学习工作的问题小助手。只关注技术,做CV领域专业的知识分享平台。