1

I have a QDockWidget with a transparent background, but I would like to change the background color or background image when it is floating. It doesn't look like the qt style sheets have a pseudo state to tell you whether or not they are floating, so I'd like to know: is this possible to do?

Nicolas Holthaus
  • 7,763
  • 4
  • 42
  • 97

2 Answers2

3

Found the solution. Add the following connection in the code:

    connect(knobDock, &QDockWidget::topLevelChanged, [&] (bool isFloating)
    {
        if (isFloating)
        {
            setAttribute(Qt::WA_TranslucentBackground, false);
            setAttribute(Qt::WA_NoSystemBackground, false); 
        }
    });

This will cause the dock widgetto use whatever background is specified in the stylesheet when the dock is floating, but it will be transparent (i.e. show the mainwindow background) when it's docked.

Nicolas Holthaus
  • 7,763
  • 4
  • 42
  • 97
0

You can use custom properties to do this.

Thanks @phyatt for link to Dynamic Properties and Stylesheets.

To declare custom property in your custom class you can write in .cpp:

setProperty("customPropertyName", 1);

or in .h (don't forget to define and implement used get/set access methods too):

Q_PROPERTY( int customPropertyName, READ getCustomPropertyName, WRITE setCustomPropertyName);

And in your global stylesheet file you can use the state of your custom property as following:

.YourClass[customPropertyName="1"] {
    background-color: transparent;
}

.YourClass[customPropertyName="2"] {
    background-color: black;
}

Also it's needed to reload stylesheet of the object instance after your set new property value, because stylesheets are not recalculated automatically:

object->style()->unpolish(tstFrame);
object->style()->polish(tstFrame);
object->update();

or:

object->setStyleSheet("/* */");
Community
  • 1
  • 1
Max Go
  • 2,092
  • 1
  • 16
  • 26
  • 1
    I have custom properties in my code in other places, but there is a serious flaw: A property change doesn't reload the style sheet, you'd have to reload and repolish it every time the property changes, which would take ~10 seconds with the textures I'm using. Your example actually also calls this a bad approach. – Nicolas Holthaus Sep 30 '14 at 20:00
  • @NicolasHolthaus, I have added at the end a note, that in case if you use global stylesheet, you can just update the stylesheet only on your object which requires recalculation, hope this helps – Max Go Sep 30 '14 at 20:15