Using variables in qt StyleSheets

前端 未结 4 1492
無奈伤痛
無奈伤痛 2021-01-04 03:31

Is there any possibility of giving variable name to hex/rgb numbers in .qss file . For eh

myColor = #FFCC08
QPushButton { background-color: myColor;}
         


        
相关标签:
4条回答
  • 2021-01-04 03:49

    You could build your own tiny Sass quite easily:

    1.Create a text file with definitions of variables. Use simple format like this:

    @myColor  = #FFDDEE
    @myColor2 = #112233 
    @myWidth  = 20px
    

    2.In qss file use variable names:

    QPushButton { 
        background-color: @myColor; 
        min-width: @myWidth;
    }
    

    3.Open both files and for each variable in definition file change its occurrence in qss file with the value (string) from the definition file. It is a simple string replacement.

    4.Apply the preprocessed qss in the app.

    This is the simplest solution. You can change both definition file and qss file outside the app and apply it without recompilation of code.

    0 讨论(0)
  • 2021-01-04 03:57

    Here is a solution using sass. First, install the python bindings:

    pip install sass
    

    Then, use it:

    import sys
    import sass
    app = QApplication(sys.argv)
    
    # Create your sass style sheet (you can also write this in a file and load the file)
    style = '''
    $bg-dark: #292929;
    
    QPushButton {
    color: red;
    background-color: $bg-dark;
    }
    '''.encode('utf-8')
    
    # Compile Sass to CSS
    style = sass.compile_string(style).decode()
    
    # And set it to your app
    app.setStyleSheet(style)
    
    0 讨论(0)
  • 2021-01-04 04:10

    Another way to accomplish this would be to use Dynamic Properties. This would let you easily assign multiple properties to an object or group of objects, sort of like assigning a css class to an object. https://wiki.qt.io/Dynamic_Properties_and_Stylesheets

    For example, in your UI file, you could add a string dynamic property "colorStyle" with a value of "myStyle1".

    Your stylesheet would look like:

    QPushButton[colorStyle='myStyle1'] {
        background-color: #FFCC08;
        ... any other style changes...
    }
    

    Any QPushButton you assign 'myStyle1' will follow the stylesheet if you set it globally.

    0 讨论(0)
  • 2021-01-04 04:14

    What you're trying to accomplish simply isn't possible using pure Qt style sheets.

    You can achieve a similar effect by modifying and reloading your style sheets from within your C++ code, for example:

    QString myColor = "#FFCC08";
    QString styleSheet = "QPushButton { background-color: %1;}";
    ...
    myWidget->setStyleSheet( styleSheet.arg(myColor) );
    

    Unfortunately this has several drawbacks (inability to preview in designer, changing code rather than a style sheet), but it's about as close as you can get to what you're trying to achieve with Qt.

    0 讨论(0)
提交回复
热议问题