PyQt5 custom personalized software interface

1. Functional overview
Qt Style Sheets (Qt Style Sheets, QSS) is a powerful mechanism for customizing user interfaces. Its concepts and terminology are inspired by Cascading Style Sheets (CSS) in HTML. .

Similar to HTML's CSS, Qt's style sheets are defined in plain text format , and these style definitions can be loaded and parsed when the application is running. Style sheets can be used to define the styles of various interface components (QWidget class and its subclasses), so that the application interface can present different effects. Many software have the function of selecting different interface themes, which can be realized by using Qt style sheets.

The editing function of Qt style sheet is integrated in UI Designer. When designing the form interface, select the form or an interface component, click the right mouse button, and select the "Change styleSheet..." menu item in the pop-up shortcut menu to display the style sheet editing dialog box.

QWidget{
    
    
     background-color: rgb(0, 85, 127);
     font: 12pt "宋体";
}

This defines the background color, font size and name of the QWidget class. This style definition will be applied to the QWidget class and its subclasses:

QLineEdit{
    
    
     border: 2px groove gray;
     border-radius: 10px;
     padding: 2px 4px;
     color: rgb(255, 255, 0);
     border-color: rgb(0, 255, 0);
}

The above defines the display effect of the QLineEdit class, including border width, radius of rounded border, border color, text color, etc.

insert image description here
The button of the drop-down menu can define some common style attributes, such as foreground color, background color background-color, selected color selection-color, background image background-image, etc.

The effect can be displayed immediately after setting the style sheet during the visual design of the form.

Qt style sheet syntax: The syntax (Syntax) of Qt style sheet is almost identical to the CSS syntax of HTML. The Qt style sheet contains a series of style rules. A style rule consists of a selector and some declarations.

QPlainTextEdit{
    
    
     font: 12pt "仿宋";
     color: rgb(255, 255, 0);
     background-color: rgb(0, 0, 0);
}

QPlainTextEdit is a selector , indicating that the style declaration in the following curly braces applies to the QPlainTextEdit class and its subclasses. The style declaration part is a list of style rules , each style rule consists of attributes and values, and each rule ends with a semicolon. Each style rule consists of " attribute: value ".
The font attribute, the font size is 12pt, and the font name is "Fan Song". When an attribute has multiple values, the multiple values ​​are separated by spaces.

Qt style sheets support all selectors defined in CSS2

Selector example use
universal selector * all components
type selector QPushButton Components of all QPushButton classes and their subclasses
attribute selector QPushButton[flat = false ] Components of the QPushButton class and its subclasses for which all flat properties are false. If the properties of the component change after the style sheet is applied, the style sheet needs to be reapplied to refresh the display effect
non-subclass selector .QPushButton All components of the QPushButton class, but not subclasses of QPushButton
ID selector QPushButton # btnOK QPushButton instance whose objectName is btnOK
Dependent object selector QDialog QPushButton All instances of the QPushButton class belonging to QDialog, that is, all QPushButtons in the QDialog dialog box
child object selector QDialog > QPushButton All instances of the QPushButton class directly subordinate to QDialog

Selectors can be combined, and a single style declaration can be applied to multiple selectors.

QPlainTextEdit,QLineEdit,QPushButton,QCheckBox{
    
    
     color: rgb(255, 255, 0);
     background-color: rgb(0, 0, 0);
}

Note: The syntax of QSS and the symbols in it have nothing to do with the Python language, so the constants representing bool values ​​in QSS are true and false, and do not use the capitalized True and False in Python.

Sub-controls: such as the drop-down button of QComboBox, the up and down buttons of QSpinBox. The display effects of these interface elements can be controlled through the sub-controls of the selector.

QComboBox::drop-down{
    
     image: url(:/images/images/down.bmp); }

The selector QComboBox::drop-down selects the drop-down sub-control of QComboBox, and the defined style is to set its image property to the picture down.bmp in the resource file.

For the list of sub-controls of Qt, see the help documentation of Qt for details.

Pseudo-state : Selectors can contain pseudo-states, so that style rules can only be applied to a certain state of the interface component, which is a conditional application rule. Pseudo-states appear after selectors, separated by a colon.

QLineEdit:hover{
    
     background-color: lime;
                    color: yellow;}

Defines when the mouse moves over the QLineEdit (hover), change the background color and foreground color of the QLineEdit.

Invert a pseudostate by preceding it with an exclamation point.

QLineEdit:!read-only{
    
     background-color: rgb(235, 255, 251); }

Defines the background color of a QLineEdit whose readonly property is false.

Pseudo-states can be used in series, which is equivalent to the calculation of logic and

QCheckBox:hover:checked{
    
     color: red; }

Defines that when the mouse moves over a checked QCheckBox component, its font color changes to red. It means that if the mouse is only moved to the QCheckBox, or the QCheckBox is only checked, the font will not turn red.

Pseudo-states can be used in parallel, which is equivalent to the calculation of logical or

QCheckBox:hover, QCheckBox:checked{
    
     color: red; }

When the mouse moves over the QCheckBox component or the QCheckBox component is checked, the font color changes to red. One of them turns red immediately when it is completed.

Child controls can also use pseudo-states

QCheckBox::indicator:checked{
    
    
          image: url(:/images/images/checked.bmp);}
QCheckBox::indicator:unchecked{
    
    
          image: url(:/images/images/unchecked.bmp);}

Defines the display pictures of the indicator of QCheckBox in the checked and unchecked states, for example, the effect of the illustration can be obtained.
insert image description here
Some common pseudo-states in Qt style definition, familiar with these pseudo-states and flexible application can define the interface effect you want.

Attributes : multiple style rules can be defined for each selector in the Qt style sheet, and each rule is an "attribute: value" pair. There are many attributes that can be defined in the Qt style sheet. You can find "Qt Style Sheets Reference" for detailed descriptions of all properties.

insert image description here
In the Edit Style Sheet dialog box, you can choose to Add Resource, Add Gradient, Add Color, and Add Font.
✔ Add resources: Select images from your project's resource files.
✔Add Colors: Various colors for setting components.
✔Add Gradients: Various gradient colors for setting components.

Each interface component can be represented by the following figure.
insert image description here
(1) content is a rectangular area for displaying content, such as the area where QLineEdit is used to display text. The max-width, min-width, max-height, and min-height attributes respectively define the maximum/minimum width and height to define this rectangular area, for example:

QLineEdit{
    
    
     min-width:50px;
     max-height:40px;
}

(2) Padding is a rectangular area surrounding the content. The width of padding can be defined through the padding attribute, or padding-top, padding-bottom, padding-left, padding-right respectively define the width of top, bottom, left and right of padding, for example :

QLineEdit{
    
     padding: 0px 10px 0px 10px;}

(3) Border is the border surrounding padding. The line width, line type and color of the border can be defined through the border attribute (or border-width, border-style, border-color), and the top, bottom and left of the border can also be defined separately , right line width and color. Use border-radius to define the arc radius of the corner of the border, so as to construct components such as edit boxes or buttons with rounded rectangles, for example:

QLineEdit{
    
    
     border-width: 2px;
     border-style: solid;
     border-color: gray;
     border-radius: 10px;
     padding: 0px 10px; 
}

(4) margin is the blank margin between the border and the parent component, which can define the margin size of top, bottom, left and right respectively.

Use of Qt style sheet :
1. The first way to use the Qt style sheet in the program
: when visually designing the UI form, directly use the style sheet editor to design the style sheet for the form or the components on the form, and the style designed in this way is saved in the .ui file of the form In the form, the style sheet designed will be automatically applied when the form is created.

The second is to use the setStyleSheet() function of the QApplication class to set the style for the application globally when the application is created.

if  __name__ == "__main__":        #用于当前窗体测试
   app = QApplication(sys.argv)    #创建GUI应用程序
   app.setStyleSheet("QLineEdit { background-color: gray }")
   form=QmyWidget()      #创建窗体
   form.show()
   sys.exit(app.exec_())

Here, the style is set for all QLineEdit components in the application. If no other styles are set for the QLineEdit components in the application, the background color of all QLineEdit components is gray.

You can also use the setStyleSheet() function of QWidget to set the style for a window, a dialog box or an interface component, which is generally set in the constructor of the form.

class QmyWidget(QWidget): 
   def __init__(self, parent=None):
       super().__init__(parent) 
      self.ui=Ui_Widget()    
      self.ui.setupUi(self)  
      self.setStyleSheet("QLineEdit { background-color: red }")

This sets the style for all QLineEdit components on this form, that is, the background color is red.

You can also call the setStyleSheet() function with a specific component, because the interface components are all subclasses of QWidget.

self.ui.editName.setStyleSheet("color: blue;"
                     "background-color: lime;"
                     "selection-color: yellow;"
                     "selection-background-color: red;")

This is the style of setting a component whose objectName is editName. Note that there is no need to set the selector name in the style sheet at this time, and the set style is only applied to the editName component.

In this way, the style sheet is fixed in the program, and it is obviously impossible to switch the interface effect. In order to dynamically switch interface effects, generally save the style sheet definition as a plain text file with a .qss suffix , then open the file in the program, read the text content, and then call the setStyleSheet() function to apply the style.

if  __name__ == "__main__":        #用于当前窗体测试
   app = QApplication(sys.argv)    #创建GUI应用程序
   file = QFile("myStyle.qss")
   file.open(QFile.ReadOnly)
   qtBytes = file.readAll()     #QByteArray
   pyBytes = qtBytes.data()     #QByteArray转换为bytes
   styleStr = pyBytes.decode("utf-8")    #bytes转换为str
   app.setStyleSheet(styleStr)

   form = QmyWidget()    #创建窗体
   form.show()
   sys.exit(app.exec_())

The file myStyle.qss in the same directory is used here, and all style definitions are stored in this file. The advantage of using style files is that if you want to change the interface effect, you only need to modify the file or switch files, just like the multilingual interface, and it is also convenient to use third-party style definition files to achieve professional interface effects.

2. Clarity of style definition
Conflicts arise when multiple style rules define different values ​​for an attribute. For example:

QPushButton#btnSave { color: gray }
QPushButton {
    
     color: red }

In the above example, QPushButton#btnSave is considered a more specific selector than QPushButton because it points to a specific object rather than all instances of QPushButton. So, if the above two rules are applied to a window, the foreground color of the btnSave button is gray, while the foreground color of other buttons is red.

Also, selectors with pseudo-states are considered more specific than selectors without pseudo-states, for example:

QPushButton:hover {
    
     color: white }
QPushButton {
    
     color: red }

In this way, the color is white when the mouse is over the button, otherwise the color is red.

If two selectors have the same specificity, the order in which the rules appear prevails, and the rule that appears later takes effect, for example:

QPushButton:hover {
    
     color: white }
QPushButton:enabled {
    
     color: red }

Both selectors here have the same specificity, so when the mouse is over an enabled button, only the second law applies. In this case, if you do not want conflicts, you should modify the rules to make them more explicit, such as the following two rules are not in conflict:

QPushButton:hover:enabled {
    
     color: white }
QPushButton:enabled {
    
     color: red }

The two classes of the parent-child relationship have the same clarity when used as selectors, for example:

QPushButton {
    
     color: red }
QAbstractButton {
    
     color: gray }

The two selectors have the same specificity, so it depends only on the order of the statements.

3. Cascading of style definitions Style
definitions can be defined in an application, a form, or a specific component. The style of any component is the fusion of the styles of its parent component, parent form and application. When a conflict occurs, the component will use the style definition closest to itself, that is, use the component's own style, the style definition of the parent component, the style definition of the parent form, or the style definition of the application in order, regardless of the style selector. Certainty.
For example, to set global styles in QApplication:

from PyQt5.QtWidgets import  qApp
qApp.setStyleSheet("QPushButton { color: red }")

Then the foreground color of all QPushButtons in the application whose style is not defined is red. qApp is a global variable representing the current application and needs to be imported from the PyQt5.QtWidgets module.

If you define a style in a form class (such as QmyWidget):

self.setStyleSheet("QPushButton { color: blue }")

Then the foreground color of the button on the form is blue, not red.

If there is a QPushButton button named btnSave on the form, its style is defined as follows:

self.ui.btnSave.setStyleSheet(
            "color: yellow; background-color: black;")

The button btnSave displays foreground and background colors in its own style.

The Qt style sheet is powerful and can design unique interface effects, but this requires good art design, and there is not much content involved in programming.

Guess you like

Origin blog.csdn.net/qq_35412059/article/details/129867280