什么是QSSQSS 是Qt StyleSheet 的简称,意思就是qt的样式表格,StyleSheet 可以像CSS一样的写样式。使页面美化跟代码层分开,利于维护。
QSS的语法同css一样,他也是由一个selector与一个declaration形成,selector指定了是对哪一个控件发生后果,而declaration才是真实的发生作用的语句。如:
QPushButton{background-color:red}
QPushButton指定了是对所有的QPushButton或是其子类控件(如用户定义的MyPushButton)发生波及,而background-color:red阐明所有的受波及控件的背景都为red。除非“类名”,“对象名”,“Qt属性名”这三样东西是大小写敏感的外其余的东西都是大小写不敏感的,如color与Color代表统一属性。万一有几个selector指定了相像的declaration, 能够运用逗号(,各种绽放准绳驱动着ATM技巧不停变动,)将各个抉择器分离,如:
QPushButton, QLineEdit, QComboBox{color:blue}
他相当于:
QPushButton{color:red}QLineEdit{color:red}QComboBox{color:red}
declaration部份是一系列的(属性:值)对,使用分号(;)将各个不同的属性值对分离,使用大括号({})将所有declaration包括在同时。
1, 平常选择器(selector)
Qt扶持所有的CSS2定义的选择器,其祥细内容可以在w3c的网站上查找http://www.w3.org/TR/CSS2/selector.html, 中间对照常用的selector类别有:
1.1 通用类型选择器:*
会对所有控件有结果。
1.2 类别选择器:QPushButton
匹配所有QPushButton的实例和其子类的实例。
1.3 属性选择器:QPushButton[flat=”false”]
匹配所有QPushButton属性flat为false的实例,属性分为两种,静态的和动态的,静态属性可以通过Q_PROPERTY() 来指定,动态属性可以使用setProperty来指定,如:
QLineEdit *nameEdit = new QLineEdit(this);
nameEdit->setProperty("mandatoryField", true);
如果在设置了qss后Qt属性变动了,必要重新设置qss来使其见效,可以使用先unset再set qss。
1.4 类选择器:.QPushButton
所有QPushButton的实例,但不包括其子类,这相当于:
*[class~="QPushButton"]
~=的含义是测验一个QStringList类别的属性是否包罗给定的QString。
1.5 ID抉择器:QPushButton#okButton
对应Qt里面的object name设置,使用这条CSS之前要先设置对应控件的object name为okButton,如:
Ok->setObjectName(tr(“okButton”));
1.6 后代选择器:QDialog QPushButton
对于所有为QDialog后代(包括儿子,与儿子的儿子的递归)为QPushButton的实例
1.7 子选择器:QDialog > QPushButton
对于所有的QDialog直接子类QPushButton的实例,不包罗儿子的儿子的递归。
更多链接: http://www.360doc.com/content/13/1106/08/12424571_327060922.shtml
关于如何写样式可参考Qt Style Sheets Examples 地址:http://doc.qt.io/qt-4.8/stylesheet-examples.html#customizing-qscrollbar
Pyqt4 examples里面也有关于QSS的例子: 路径:pyqt4_examples\widgets\stylesheet\stylesheet.py
实例样式可以添加到代码页面,也可以分离为单独文件
资源图片:
1. 这是一个样式和代码在同一页面的Example:
1#-*- coding: utf-8 -*-2fromPyQt4importQtCore, QtGui3fromPyQt4.QtGuiimport*4fromPyQt4.QtCoreimport*5importsys6importqr789try:10_fromUtf8 =QtCore.QString.fromUtf811exceptAttributeError:12def_fromUtf8(s):13returns1415try:16_encoding =QtGui.Qapplication.UnicodeUTF817def_translate(context, text, disambig):18returnQtGui.QApplication.translate(context, text, disambig, _encoding)19exceptAttributeError:20def_translate(context, text, disambig):21returnQtGui.QApplication.translate(context, text, disambig)2223242526classMainStyle(QWidget):27def__init__(self, parent=None):28super(MainStyle, self).__init__(parent)29self.setWindowFlags(Qt.FramelessWindowHint)30self.resize(200, 300)31self.btn_close =QPushButton()32self.btn_close.setStyleSheet("""QPushButton{background-image:url(./img/btn_close_normal.png);width:39px;height:18px;padding-top:0px;border:0px;}33QPushButton:hover{background-image:url(./img/btn_close_highlight.png);}34QPushButton:pressed{background-image:url(./img/btn_close_down.png);}""")3536self.btn_min =QPushButton()37self.btn_min.setStyleSheet("QPushButton{background-image:url(./img/btn_close_normal1.png);width:39px;height:18px;padding-top:0px;border:0px;}")3839self.btn_setting =QPushButton()40self.btn_setting.setStyleSheet("""QPushButton{background-image:url(./img/icon_cog.png);width:16px;height:16px;padding-top:0px;border:0px;margin-right:15px;}41QPushButton:hover{background-image:url(./img/icon_cogs.png);}""")4243self.btn_photo =QPushButton()44self.btn_photo.setStyleSheet("""QPushButton{background-image:url(./img/photo.png);width:32px;height:26px; border-radius: 10px;45margin-right:60px;}""")#border-radius 元素添加圆角边框!4647#按钮样式一48btn_one=QtGui.QPushButton(u"按钮样式一", self)49btn_one.setGeometry(0, 100,100, 200)50btn_one.setStyleSheet("QPushButton{background-color:blue;border:none;color:#ffffff;font-size:20px;}"51"QPushButton:hover{background-color:#333333;}")52#按钮样式二53btn_two=QtGui.QPushButton(u"按钮样式二", self)54btn_two.setGeometry(100,100, 101, 200)55btn_two.setStyleSheet("QPushButton{background-color:#D30000;border:none;color:#ffffff;font-size:20px;}"56"QPushButton:hover{background-color:#333333;}")5758#顶部布局59self.topBarLayout =QtGui.QHBoxLayout()60self.topBarLayout.addStretch()61self.topBarLayout.addWidget(self.btn_photo,0,Qt.AlignRight |Qt.AlignHCenter)62self.topBarLayout.addWidget(self.btn_setting,0,Qt.AlignRight |Qt.AlignHCenter)63self.topBarLayout.addWidget(self.btn_min,0,Qt.AlignRight |Qt.AlignTop)64self.topBarLayout.addWidget(self.btn_close,0,Qt.AlignRight |Qt.AlignTop)65#main布局66self.mainLayout =QtGui.QVBoxLayout()67self.mainLayout.addLayout(self.topBarLayout,0)68self.mainLayout.addStretch()69self.mainLayout.addStretch()70self.setLayout(self.mainLayout)71self.mainLayout.setContentsMargins(0,0,0,0)72self.mainLayout.setSpacing(0)7374self.connect(self.btn_close,QtCore.SIGNAL("clicked()"),QtGui.qApp,QtCore.SLOT("quit()"))7576777879defpaintEvent(self,event):80self.painter =QtGui.QPainter()81self.painter.begin(self)82self.painter.drawPixmap(self.rect(), QPixmap("./img/mianbg.png"))83self.painter.end()8485#支持窗口拖动,重写两个方法86defmousePressEvent(self, event):87ifevent.button()==Qt.LeftButton:88self.m_drag=True89self.m_DragPosition=event.globalPos()-self.pos()90event.accept()9192defmouseMoveEvent(self, QMouseEvent):93ifQMouseEvent.buttons()andQt.LeftButton:94self.move(QMouseEvent.globalPos()-self.m_DragPosition)95QMouseEvent.accept()9697defmouseReleaseEvent(self, QMouseEvent):98self.m_drag=False99100101102103if__name__=='__main__':104app =QApplication(sys.argv)105main =MainStyle()106main.show()107app.exec_()
效果:
2.这是一个样式和代码分离的Example:
在Qt Designer 中也可以添加样式
但,我们现在不使用Qt Designer 填写,我们使用外部qss文件
新建文件命名为css.qss
内容如下:
QPushButton#pushButton{background-image:url(:/cssimg/img/btn_close_normal.png);width:39px;height:18px;padding-top:0px;border:0px;}QPushButton#pushButton:hover{background-image:url(:/cssimg/img/btn_close_highlight.png);}QPushButton#pushButton:pressed{background-image:url(:/cssimg/img/btn_close_down.png);}QPushButton#pushButton_2{background-image:url(:/cssimg/img/icon_cog.png);width:16px;height:16px;padding-top:0px;border:0px;margin-right:15px;}QPushButton#pushButton_2:hover{background-image:url(:/cssimg/img/icon_cogs.png);}
通过传入路径\文件名的方式创建一个QFile对象,以readonly的方式打开,然后readAll,最后QtGui.qApp.setStyleSheet(styleSheet)就可以使qss生效。
在要引用的页面添加:
1file = QtCore.QFile('css.qss')2file.open(QtCore.QFile.ReadOnly)3styleSheet =file.readAll()4styleSheet = unicode(styleSheet, encoding='utf8')5QtGui.qApp.setStyleSheet(styleSheet)
完整代码如下:
1#-*- coding: utf-8 -*-23#Form implementation generated from reading ui file 'css2.ui'4#5#Created: Sat May 30 15:47:25 20156#by: PyQt4 UI code generator 4.10.37#8#WARNING! All changes made in this file will be lost!910fromPyQt4importQtCore, QtGui1112try:13_fromUtf8 =QtCore.QString.fromUtf814exceptAttributeError:15def_fromUtf8(s):16returns1718try:19_encoding =QtGui.QApplication.UnicodeUTF820def_translate(context, text, disambig):21returnQtGui.QApplication.translate(context, text, disambig, _encoding)22exceptAttributeError:23def_translate(context, text, disambig):24returnQtGui.QApplication.translate(context, text, disambig)2526classUi_MainWindow(object):27defsetupUi(self, MainWindow):28MainWindow.setObjectName(_fromUtf8("MainWindow"))29MainWindow.resize(446, 380)30self.centralwidget =QtGui.QWidget(MainWindow)31self.centralwidget.setObjectName(_fromUtf8("centralwidget"))32self.pushButton_2 =QtGui.QPushButton(self.centralwidget)33self.pushButton_2.setGeometry(QtCore.QRect(350, 20, 31, 16))34self.pushButton_2.setStyleSheet(_fromUtf8(""))35self.pushButton_2.setText(_fromUtf8(""))36self.pushButton_2.setObjectName(_fromUtf8("pushButton_2"))37self.pushButton =QtGui.QPushButton(self.centralwidget)38self.pushButton.setGeometry(QtCore.QRect(390, 20, 39, 18))39self.pushButton.setCursor(QtGui.QCursor(QtCore.Qt.WaitCursor))40self.pushButton.setMouseTracking(False)41self.pushButton.setAutoFillBackground(False)42self.pushButton.setStyleSheet(_fromUtf8(""))43self.pushButton.setText(_fromUtf8(""))44self.pushButton.setObjectName(_fromUtf8("pushButton"))45MainWindow.setCentralWidget(self.centralwidget)46self.statusbar =QtGui.QStatusBar(MainWindow)47self.statusbar.setObjectName(_fromUtf8("statusbar"))48MainWindow.setStatusBar(self.statusbar)4950self.retranslateUi(MainWindow)51QtCore.QMetaObject.connectSlotsByName(MainWindow)5253defretranslateUi(self, MainWindow):54MainWindow.setWindowTitle(_translate("MainWindow","MainWindow", None))55file = QtCore.QFile('css.qss')56file.open(QtCore.QFile.ReadOnly)57styleSheet =file.readAll()58styleSheet = unicode(styleSheet, encoding='utf8')59QtGui.qApp.setStyleSheet(styleSheet)6061importqr6263if__name__=="__main__":64importsys65app =QtGui.QApplication(sys.argv)66MainWindow =QtGui.QMainWindow()67ui =Ui_MainWindow()68ui.setupUi(MainWindow)69MainWindow.show()70sys.exit(app.exec_())
效果: