Pregunta

This should set the background to cats.jpg, but it doesn't do anything:

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w; 
    w.setStyleSheet("background-image: url(images/ricepaper.png);");;

    w.show();

    return a.exec();
}

I thought that it could be a problem with the image location since changing the widget's background-color works fine, but the images folder is in the build-debug directory which I believe is the correct place. I've tried changing the image path, syntax, and styleSheet class and nothing has worked, any suggestions?

¿Fue útil?

Solución

From Qt Style Sheets Reference:

enter image description here

It should work. Probably the image file is not to be found where the program expects. If you're using Qt Creator, you should be aware that it builds the target binary in a separate directory (usually with a name like build-yourprojectname-qtversion-Debug or so). That's called shadow build. You'll need to copy over your image(s) to the proper location relative to that shadow build directory, otherwise the program will not be able to find the file.

Your best bet is to embed the image in the binary as a resource. I just tried this and seems to be working for me:

In main.cpp:

int main(int argc, char *argv[])
{

   QApplication app(argc, argv);

   QWidget *w = new QWidget;
   w->setStyleSheet("background-image: url(:/resources/pixmaps/close.png);");

   w->show();

   return app.exec();
}

Note the :/ part in url(:/resources/pixmaps/close.png). That's needed for embedded resources.

In resources.qrc:

<RCC>
<qresource prefix="/">
    <file>resources/pixmaps/close.png</file>

    ... other resource files go here
</qresource>

At the end of testproject.pro:

   RESOURCES += \
   resources.qrc

Of course you'll need to put the images in the proper location in your project directory so that the resource compiler can find it. In my example,

 resources/
 ├── pixmaps
 │   ├── application.png
 │   ├── cancel.png
 │   ├── close.png    <--Here
 ...

enter image description here

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top