How to change background-color of widget, but not items



  • I would like to create a widget with a background color, but I do not want to change the color of the buttons & comboboxes.

    I already tried this:

    QString style = "background-color: #D8A09F";
    this->setStyleSheet(style);
    

    which sets the background to the color I desire but it also changes the color of any item in the widget.
    Would somebody like to help me out?
    Thanks!



  • @hobbyProgrammer
    I do not know whether this would make the difference, but if you widget is of some type YourWidget you could try QString style = "YourWidget { background-color: #D8A09F; }"; to see if by applying that to the specified widget stops it propagating to child widgets?

    [Looks like @J-Hilk types faster than I can... :) ]


  • Moderators

    hi @hobbyProgrammer
    by using specifiers of course :)

    first of define the Qt Widget type you want to target e.G. QPushButton

    QString style = "QPushButton{background-color: #D8A09F;}"
    

    now you can further narrow it down by using the objectName property. Widgets added via QtDesigner always have a unique objectName. Widgets created and added via Code do not have one by default, and you'll have to set it first.

    for example your QPushButton has the objectName btnHome

    QString style = "QPushButton#btnHome{background-color: #D8A09F;}"
    


  • @hobbyProgrammer
    I do not know whether this would make the difference, but if you widget is of some type YourWidget you could try QString style = "YourWidget { background-color: #D8A09F; }"; to see if by applying that to the specified widget stops it propagating to child widgets?

    [Looks like @J-Hilk types faster than I can... :) ]


  • Moderators

    @JonB said in How to change background-color of widget, but not items:

    [Looks like @J-Hilk types faster than I can... :) ]

    Sometimes, but I imagine I write with more errors as well :)


Log in to reply