cannot change the QWidget background image.

  • Hey fellas, I've tried to change the background image of a QWidget, so I simply subclass-ed QWidget, and call this->setStyleSheet("QWidget {background-image: url(c:/mybackground.png) }"); in the initializaiton function. it seems nothing has happened.

    But then I found out accidentally that if I deleted the declaration of Macro Q_OBJECT in the declaration of the class, the background will be actually replaced by the desired image. But I need this Macro in a normal QApplication.

    how could it happen? is there any possibility to change the background image via the "this pointer"?

    thnx in advance!

  • Qt Champions 2017

    You dont need to subclass QWidget to set stylesheet
    ui->somewidget->setStyleSheet will do 100% the same
    this->setStyleSheet inside a subclass.

    What is wrong is most likely the path "c:/"
    You are pointing to c:. not sure it will load it.
    Normally you would add a qresource file
    New->Qt->Qt resource file
    To that new file via right click and Add existing file you add your bg image.
    then syntax is then
    background-image: url(:/bg.png);
    ( with rest as is.) notice the ":/"

    please see this sample

    right click the widget to see the stylesheet. There is menu when in

  • @mrjj hey, thnx for the reply. not familiar with qt designer though, i'll have a look.

  • Qt Champions 2017

    Well I hope your version have the StyleSheet editor. very handy for
    crafting stylesheets and see the effect at once.

  • @mrjj said:

    hi I tried to add qt source file. oddly enough the same thing happened, once I deleted the Q_OBJECT Macro, the background will be set correctly, if this Macro is declared the background will not be changed.

    I'll try the qt designer afterwards. I'll give a feed back afterwards.

  • Qt Champions 2017

    @qtpi said:


    You will most likely want this so i hope the qrc works for you.

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.