本篇将介绍调色板QPalette的应用和文本对齐的设置,还涉及到字体QFont的设定。
QPalette可设定控件的背景色或背景图片,还可设定文本的颜色。它可替代上一篇讲到的样式表StyleSheet的部分功能。
palette = QPalette()#创建调色板对象。
palette.setColor()可以选择不同的参数创建背景色,文本颜色
palette.setBrush()可以设置背景图片
但是,要使背景色或背景图片起作用,必须调用控件的setAutoFillBackground()方法,并将参数设为True。
最后,调用控件的setPalette()方法,指定调色板。
控件的setAlignment()方法可以设定文本的对齐。具体参数详见代码注释。
本篇还是仅以QLable作为例子讲解。代码的显示效果如下图:
代码如下,建议在浏览器中打开,并使用横屏阅读。
# _*_ coding:utf-8_*_ #调色板和文字的对齐 import sys from PyQt5.QtGui import * from PyQt5.QtWidgets import * from PyQt5.QtCore import Qt
class MyWidget(QWidget):#创建一个QWidget的 子类 def __init__(self,parent = None):#初始化函数 super().__init__(parent)#调用基类的初始化函数 self.initUI()
def initUI(self): labels = list() glayout = QGridLayout() #创建字体对象(SansSerif',大小20,加粗、斜体) font = QFont('SansSerif',pointSize = 20, weight =QFont.Bold,italic =True) #font.setFamily(u"Arial") rows, cols = 3, 3 for i in range(rows): for j in range(cols): label = QLabel(u"Label%s"%(cols*i+j+1)) if i == 0: palette1 = QPalette()#新建调色板 palette1.setColor(QPalette.Window,QColor(0,100,80*j))#背景色 palette1.setColor(QPalette.WindowText,QColor(255,0,0))#文本颜色 label.setAutoFillBackground(True)#须设置自动填充背景色,否则不能改变背景 label.setPalette(palette1)#指定调色板 label.setFixedHeight(50) elif i == 1: palette2 = QPalette() palette2.setBrush(QPalette.Window,QBrush(QPixmap("ICON/smile.png")))#背景图片 palette2.setColor(QPalette.WindowText,QColor(0,100,250))#文本颜色 label.setAutoFillBackground(True)#须设置自动填充背景色,否则不能改变背景 label.setPalette(palette2) label.setFont(font)#指定字体 label.setFrameStyle(QFrame.Panel|QFrame.Raised) #设置样式 labels.append(label) glayout.addWidget(label,i,j,1,1)
#文本的对齐 labels[0].setAlignment(Qt.AlignLeft)#水平靠左 labels[1].setAlignment(Qt.AlignHCenter)#水平居中 labels[2].setAlignment(Qt.AlignRight)#水平靠右 labels[3].setAlignment(Qt.AlignJustify)#水平自动调整 labels[4].setAlignment(Qt.AlignTop)#垂向居顶 labels[5].setAlignment(Qt.AlignVCenter)#垂向居中 labels[6].setAlignment(Qt.AlignBottom)#垂向居底 labels[7].setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)#水平居中且垂向居中 labels[8].setAlignment(Qt.AlignRight | Qt.AlignVCenter)#水平靠右且垂向居中 #self.setPalette(palette1) self.setLayout(glayout) self.setGeometry(500,300,600,400)# 设置坐标x, y 以及宽和高 self.setWindowTitle(u'调色板和文字对齐')#设置窗口标题
if __name__== '__main__': app= QApplication(sys.argv) widget= MyWidget() widget.show() #显示到屏幕 sys.exit(app.exec_())
本文分享自 Python可视化编程机器学习OpenCV 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有