QDockWidget change background color when floating

烂漫一生 提交于 2019-12-13 00:44:05

问题


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?


回答1:


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.




回答2:


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("/* */");


来源:https://stackoverflow.com/questions/26128664/qdockwidget-change-background-color-when-floating

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!