This is happening

I use StyleSheet to set the background for the Widget, but as soon as I write

setStyleSheet("QWidget{background-image:url(./room.jpg);background-size:contain}"); 

..., I get the result, as in the picture. I think this is due to the Layout. What if I can not remove Layout, but I need a background?

    1 answer 1

    The placement manager has nothing to do with it. The background is set for all QWidget , as well as their heirs, which consequently leads to such a pleasing mosaic.

    It is necessary to specify the purpose for which the background should be set. If we are talking about QMainWindow , then we specify this particular class:

     setStyleSheet("QMainWindow{background-image:url(./room.jpg);}"); 

    ..., if the dialogue, respectively:

     setStyleSheet("QDialog{background-image:url(./room.jpg);}"); 

    Sometimes widgets of the same type can be several, and then just indicating the class is no longer necessary. In this case, you can give a name to the object, and then use that name for the target style indication. For example:

     setStyleSheet( "QDialog#dlg1{" \ "background-image:url(./room1.jpg);" \ "}" \ "QDialog#dlg2{" \ "background-image:url(./room2.jpg);" \ "}" ); QDialog dlg1, dlg2; dlg1.setObjectName("dlg1"); dlg2.setObjectName("dlg2"); 

    You can read more about the rules for using selectors in the Qt help .

    From myself I want to add that it is better not to insert styles directly into cpp-files. It is better to have some separate file my_style.qss :

     QWidget#my_wdg { color: silver; background-color: transparent; } 

    Well, somewhere in main.cpp to load and install your own style:

     int main(int argc, char *argv[]) { QApplication app(argc, argv); { QFile file("my_style.qss"); if(file.open(QFile::ReadOnly)) app.setStyleSheet(file.readAll()); } QWidget wdg; wdg.setObjectName("my_wdg"); wdg.show(); return app.exec(); }