Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

[SOLVED] Adding consecutive stylesheets to widget



  • Hello all!

       I'm using a single stylesheet to apply styles to all my widgets. My qss code is,
    

    @
    QLabel#heading
    {
    font-size: 28px;
    font-weight: bold;
    font-family: "Arial Narrow";
    }

    QLabel#colorgreen
    {
    color: green;
    }

    QLabel#colorblack
    {
    color:black;
    }
    @

    And in my source file, I want to call both 'heading' and 'colorgreen' or ' colorblack' depending on my color requirements. I have,

    @
    ui->channel_name->setObjectName("heading");
    ui->channel_name->setStyleSheet("");
    ui->channel_name->setObjectName("blackcolor");
    ui->channel_name->setStyleSheet("");
    @

    However, only the color changes to black. The styles under 'heading' is not applied. Does anyone know why? Please help me out.
    Thanks.



  • It is because your using 'id' in every CSS element. So you need all the properties to be declare under the id. Unless you using id and class together.

    @QLabel #colorgreen
    {
        font-size: 28px;
        font-weight: bold;
        font-family: "Arial Narrow"
        color: green;
    }
     
    QLabel #colorblack
    {
        font-size: 28px;
        font-weight: bold;
        font-family: "Arial Narrow"
        color:black;
    }@
    


  • I don't want to club all the properties together. I will be using a different assortment of properties each time. Clubbing them together will result in heavy repetition of code. Is there any other way out?



  • Hmmm...I think in this case you should using CSS like this:

    @QLabel {
    font-size: 28px;
    font-weight: bold;
    font-family: "Arial Narrow"
    }

    #colorgreen
    {
    color: green;
    }

    #colorblack {
    color:black;
    }@

    It is basically mean all QLabel will have all properties in QLabel {..} .

    And when you set objectName either (#colorgreen or #colorblack) then it will change the color -- also combine with all QLabel's properties.



  • Ah yes! Why didn't I think of this? Thank you so much for the solution Fahmy.


Log in to reply