9

I'm running my Qt app through command line with a parameter -stylesheet. The styles for the controls work but not when I'm trying to load a background image for the MainWindow. I tried:

QMainWindow{
background-image:url(:image_256_8bit_latest_back.png);
}

Also tried removing the ":" in background, but doesn't make a difference. Can somebody tell me what's wrong with this StyleSheet?

Jérôme
  • 26,567
  • 29
  • 98
  • 120
Owen
  • 4,063
  • 17
  • 58
  • 78

2 Answers2

21

Where is located the image you are trying to use ?

Did you put it as a resource of your application ?

If you want to use an image which is part of your resources, you should have a resource file (*.qrc) in your project. This file should contain something like this :

<RCC>
   <qresource prefix="/images">
      <file alias="sunset.jpg">sunset.jpg</file>
   </qresource>
</RCC>

Then, you could write this code in the constructor of your QMainWindow :

setStyleSheet("background-image: url(:/images/sunset.jpg);");

If you don't want to use the Qt resource system, you can just put the path to your image on your disk :

setStyleSheet("background-image: url(res/images/sunset.jpg);");

Be careful though if you are using a relative path : Qt will start from the current location, which might change, particularly if you are developping with Qt Creator.

With Qt Creator, when you run your app in debug mode, the current path is in debug/. When you run your app in release mode, the current path is in release/ (unless you changed the settings).

Tarod
  • 6,732
  • 5
  • 44
  • 50
Jérôme
  • 26,567
  • 29
  • 98
  • 120
  • 1
    thanks for the info :). But the reason why I want a separate QSS file is because I want the users to be able to customize the application by simply loading their own QSS file. So that when ran on the command prompt it could easily apply all the styles from the QSS file without having to touch the code... – Owen Dec 16 '10 at 10:23
  • 1
    That means the image is somewhere on the disk. But by starting the path with `:` tells Qt the image is a resource. Have you tried putting the absolute image path in your stylesheet ? – Jérôme Dec 16 '10 at 11:01
  • I tried to create a file called `stylesheet.qss`, located in my app folder, which contains something like this : `QMainWindow { background-image : url(sunset.jpg); }`. I run the app with the argument `-stylesheet=stylesheet.qss` and the background of my app is the sunset picture. I don't get why this isn't working for you. – Jérôme Dec 16 '10 at 14:58
1

Clearly there is a problem with the path to your image. Try using an absolute path to verify the image is loaded by QT and working.

koan
  • 3,596
  • 2
  • 25
  • 35