Pyqt QSS simple Ui beautification, pyqtqssui

Source: Internet
Author: User

Pyqt QSS simple Ui beautification, pyqtqssui
What is QSS?

QSS is short for Qt StyleSheet, which means qt style sheets. StyleSheet can be written like CSS. Separating page beautification from code layers facilitates maintenance.

 

QSS syntax

Like css, selector is also formed by a selector and a declaration. selector specifies which control has a consequence, and declaration is the actual statement. For example:

QPushButton { background-color: red }

QPushButton specifies that all QPushButton or its subclass controls (such as user-defined MyPushButton) are affected, while background-color: red indicates that the background of all affected controls is red. Unless the "Class Name", "Object Name", and "Qt attribute name" are case-sensitive, other things are case-insensitive, for example, color and Color indicate unified attributes. In case several selectors specify similar declaration, they can use commas (, various bloom standards drive the ATM technique to keep changing) to separate each selector, such:

QPushButton, QLineEdit, QComboBox { color: blue }

It is equivalent:

QPushButton { color: red }QLineEdit { color: red }QComboBox { color: red }

The declaration part is a series of (attribute: Value) pairs, which use semicolons (;) to separate different attribute value pairs and use braces ({}) to include all the declaration at the same time.

1. selector)
Qt supports all CSS2-defined selectors. The detailed content can be found on the w3c website.Http://www.w3.org/TR/CSS2/selector.html, Common selector categories include:
1.1 General type selector :*
All controls are returned.
1.2 category selector: QPushButton
Matches all QPushButton instances and Their subclass instances.
1.3 attribute selector: QPushButton [flat = "false"]
Matches all instances whose QPushButton attribute flat is false. There are two types of attributes: Static and Dynamic. Static attributes can be specified through Q_PROPERTY (), and dynamic attributes can be specified using setProperty, for example:

QLineEdit *nameEdit = new QLineEdit(this);nameEdit->setProperty("mandatoryField", true);

If the Qt attribute changes after the qss is set, you need to reset the qss to make it take effect. You can use unset before setting the qss.

1.4 class selector:. QPushButton
All QPushButton instances, but do not include their subclasses, which is equivalent:

*[class~="QPushButton"]

~ = Indicates whether the attribute of a QStringList class includes the given QString.
1.5 ID selector: QPushButton # okButton
Corresponds to the object name settings in Qt. before using this CSS, you must set the object name of the corresponding control to okButton, for example:

Ok->setObjectName(tr(“okButton”));

1.6 descendant selector: QDialog QPushButton
All instances with QDialog descendants (including the son and the son recursion) being QPushButton
1.7 Sub-selector: QDialog> QPushButton
For all QDialog directly subclass QPushButton instances, do not include the recursion of the son.

 

More links: http://www.360doc.com/content/13/1106/08/12424571_327060922.shtml

 

For how to write styles, see Qt Style Sheets Examples address: http://doc.qt.io/qt-4.8/stylesheet-examples.html#customizing-qscrollbar


In Pyqt4 examples, there are also examples of QSS: Path:Pyqt4_examples \ widgets \ stylesheet. py

 

Instance

Styles can be added to the code page or separated into separate files.

Resource image:

1. This is an Example of a style and Code on the same page:

1 #-*-coding: UTF-8-*-2 from PyQt4 import QtCore, QtGui 3 from PyQt4.QtGui import * 4 from PyQt4.QtCore import * 5 import sys 6 import qr 7 8 9 try: 10 _ fromUtf8 = QtCore. QString. fromUtf8 11 failed t AttributeError: 12 def _ fromUtf8 (s): 13 return s 14 15 try: 16 _ encoding = QtGui. QApplication. unicodeUTF8 17 def _ translate (context, text, disambig): 18 return QtGui. QApplication. translate (context, t Ext, disambig, _ encoding) 19 TB AttributeError: 20 def _ translate (context, text, disambig): 21 return QtGui. QApplication. translate (context, text, disambig) 22 23 24 25 26 class MainStyle (QWidget): 27 def _ init _ (self, parent = None): 28 super (MainStyle, self ). _ init _ (parent) 29 self. setWindowFlags (Qt. framelessWindowHint) 30 self. resize (200,300) 31 self. btn_close = QPushButton () 32 self. btn_cl Ose. setStyleSheet ("" QPushButton {background-image: url (. /img/btn_close_normal.png); width: 39px; height: 18px; padding-top: 0px; border: 0px;} 33 QPushButton: hover {background-image: url (. /img/btn_close_highlight.png);} 34 QPushButton: pressed {background-image: url (. /img/btn_close_down.png);} "") 35 36 self. btn_min = QPushButton () 37 self. btn_min.setStyleSheet ("QPushButton {background-image: url (. /img/btn_close _ Normal1.png); width: 39px; height: 18px; padding-top: 0px; border: 0px;} ") 38 39 self. btn_setting = QPushButton () 40 self. btn_setting.setStyleSheet ("" QPushButton {background-image: url (. /img/icon_cog.png); width: 16px; height: 16px; padding-top: 0px; border: 0px; margin-right: 15px;} 41 QPushButton: hover {background-image: url (. /img/icon_cogs.png);} ") 42 43 self. btn_photo = QPushButton () 44 self. btn_photo.setStyleSh Eet ("QPushButton {background-image: url (. /img/photo.png); width: 32px; height: 26px; border-radius: 10px; 45 margin-right: 60px ;}""") # Add a border to the border of the border in the border-radius element! 46 47 # button style 48 btn_one = QtGui. QPushButton (u "button style 1", self) 49 btn_one.setGeometry (0,100,100,200) 50 btn_one.setStyleSheet ("QPushButton {background-color: blue; border: none; color: # ffffff; font-size: 20px;} "51" QPushButton: hover {background-color: #333333 ;}") 52 # button style 2 53 btn_two = QtGui. QPushButton (u "button style 2", self) 54 btn_two.setGeometry (100,100,101,200) 55 btn_two.setStyleSheet ("QPushButton {background-color: # D30000; border: none; color: # ffffff; font-size: 20px;} "56" QPushButton: hover {background-color: #333333 ;}") 57 58 # top layout 59 self. topBarLayout = QtGui. QHBoxLayout () 60 self. topBarLayout. addStretch () 61 self. topBarLayout. addWidget (self. btn_photo, 0, Qt. alignRight | Qt. alignHCenter) 62 self. topBarLayout. addWidget (self. btn_setting, 0, Qt. alignRight | Qt. alignHCenter) 63 self. topBarLayout. addWidget (self. btn_min, 0, Qt. alignRight | Qt. alignTop) 64 self. topBarLayout. addWidget (self. btn_close, 0, Qt. alignRight | Qt. alignTop) 65 # main layout 66 self. mainLayout = QtGui. QVBoxLayout () 67 self. mainLayout. addLayout (self. topBarLayout, 0) 68 self. mainLayout. addStretch () 69 self. mainLayout. addStretch () 70 self. setLayout (self. mainLayout) 71 self. mainLayout. setContentsMargins (0, 0, 0, 0) 72 self. mainLayout. setSpacing (0) 73 74 self. connect (self. btn_close, QtCore. SIGNAL ("clicked ()"), QtGui. qApp, QtCore. SLOT ("quit ()") 75 76 77 78 79 def paintEvent (self, event): 80 self. painter = QtGui. QPainter () 81 self. painter. begin (self) 82 self. painter. drawPixmap (self. rect (), QPixmap (". /img/mianbg.png ") 83 self. painter. end () 84 85 # supports window dragging. Rewrite two methods: 86 def mousePressEvent (self, event): 87 if event. button () = Qt. leftButton: 88 self. m_drag = True 89 self. m_DragPosition = event. globalPos ()-self. pos () 90 event. accept () 91 92 def mouseMoveEvent (self, QMouseEvent): 93 if QMouseEvent. buttons () and Qt. leftButton: 94 self. move (QMouseEvent. globalPos ()-self. m_DragPosition) 95 QMouseEvent. accept () 96 97 def mouseReleaseEvent (self, QMouseEvent): 98 self. m_drag = False 99 100 101 102 103 if _ name _ = '_ main _': 104 app = QApplication (sys. argv) 105 main = MainStyle () 106 main. show () 107 app.exe c _()

Effect:

 

 

2. This is an Example of style and code separation:

 

You can also add styles in Qt Designer.

However, we do not use Qt Designer to fill in now. We use an external qss File

 

Name the new file css. qss.

The content is as follows:

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);}

Create a QFile object by passing in the path \ file name, open it in readonly mode, and then readAll. Finally, QtGui. qApp. setStyleSheet (styleSheet) can make the qss take effect.

Add:

1         file = QtCore.QFile('css.qss')2         file.open(QtCore.QFile.ReadOnly)3         styleSheet = file.readAll()4         styleSheet = unicode(styleSheet, encoding='utf8')5         QtGui.qApp.setStyleSheet(styleSheet)

The complete code is as follows:

 1 # -*- coding: utf-8 -*- 2  3 # Form implementation generated from reading ui file 'css2.ui' 4 # 5 # Created: Sat May 30 15:47:25 2015 6 #      by: PyQt4 UI code generator 4.10.3 7 # 8 # WARNING! All changes made in this file will be lost! 9 10 from PyQt4 import QtCore, QtGui11 12 try:13     _fromUtf8 = QtCore.QString.fromUtf814 except AttributeError:15     def _fromUtf8(s):16         return s17 18 try:19     _encoding = QtGui.QApplication.UnicodeUTF820     def _translate(context, text, disambig):21         return QtGui.QApplication.translate(context, text, disambig, _encoding)22 except AttributeError:23     def _translate(context, text, disambig):24         return QtGui.QApplication.translate(context, text, disambig)25 26 class Ui_MainWindow(object):27     def setupUi(self, MainWindow):28         MainWindow.setObjectName(_fromUtf8("MainWindow"))29         MainWindow.resize(446, 380)30         self.centralwidget = QtGui.QWidget(MainWindow)31         self.centralwidget.setObjectName(_fromUtf8("centralwidget"))32         self.pushButton_2 = QtGui.QPushButton(self.centralwidget)33         self.pushButton_2.setGeometry(QtCore.QRect(350, 20, 31, 16))34         self.pushButton_2.setStyleSheet(_fromUtf8(""))35         self.pushButton_2.setText(_fromUtf8(""))36         self.pushButton_2.setObjectName(_fromUtf8("pushButton_2"))37         self.pushButton = QtGui.QPushButton(self.centralwidget)38         self.pushButton.setGeometry(QtCore.QRect(390, 20, 39, 18))39         self.pushButton.setCursor(QtGui.QCursor(QtCore.Qt.WaitCursor))40         self.pushButton.setMouseTracking(False)41         self.pushButton.setAutoFillBackground(False)42         self.pushButton.setStyleSheet(_fromUtf8(""))43         self.pushButton.setText(_fromUtf8(""))44         self.pushButton.setObjectName(_fromUtf8("pushButton"))45         MainWindow.setCentralWidget(self.centralwidget)46         self.statusbar = QtGui.QStatusBar(MainWindow)47         self.statusbar.setObjectName(_fromUtf8("statusbar"))48         MainWindow.setStatusBar(self.statusbar)49 50         self.retranslateUi(MainWindow)51         QtCore.QMetaObject.connectSlotsByName(MainWindow)52 53     def retranslateUi(self, MainWindow):54         MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))55         file = QtCore.QFile('css.qss')56         file.open(QtCore.QFile.ReadOnly)57         styleSheet = file.readAll()58         styleSheet = unicode(styleSheet, encoding='utf8')59         QtGui.qApp.setStyleSheet(styleSheet)60 61 import qr62 63 if __name__ == "__main__":64     import sys65     app = QtGui.QApplication(sys.argv)66     MainWindow = QtGui.QMainWindow()67     ui = Ui_MainWindow()68     ui.setupUi(MainWindow)69     MainWindow.show()70     sys.exit(app.exec_())

Effect:

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.