Edit: The problem is not solved yet, I used @Scheffs answer as a workaround temporarily.
Is it possible to add an image as a background to a Qt widget application created with QWidget as a base class? I'm not using QMainWindow here at all.
In Qt Creator, you can generate skeleton source code files while creating a new project. If you choose QWidget as a base class, and you try to add an image as a background by changing the widgets style sheet (wither manually or from the design section of the IDE), The image doesn't show up when you build the project. How can I fix this if it's possible?
I create a Qt Resource File, add an image (which is in the source code directory), and set the style sheet, That's it. But if I add a background color with
Widget->setStyleSheet(QString::fromUtf8("#Widget {background-color: rgb(55,55,55)};"));
in ui_widget.h, It works fine and shows up after build.
And if I preview the widget from inside Qt Creator, the image appears, but doesn't after building and running.
Here you choose QWidget as a Base class in Qt Creator:
This is main.cpp:
#include "widget.h"
#include <QtCore/qglobal.h>
#include <QtWidgets/QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}
This is ui_widget.h:
#include <QtCore/QVariant>
#include <QtWidgets/QApplication>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_Widget
{
public:
void setupUi(QWidget *Widget)
{
if (Widget->objectName().isEmpty())
Widget->setObjectName(QString::fromUtf8("Widget"));
Widget->resize(600, 150);
// I add this line, if I changed the style sheet to a simple background color it shows up with no problem {background-color: rgb(1,1,200)}
Widget->setStyleSheet(QString::fromUtf8("#Widget {background-image: url(:/pic.jpg);}"));
retranslateUi(Widget);
QMetaObject::connectSlotsByName(Widget);
} // setupUi
void retranslateUi(QWidget *Widget)
{
Widget->setWindowTitle(QApplication::translate("Widget", "Widget", nullptr));
} // retranslateUi
};
namespace Ui {
class Widget: public Ui_Widget {};
} // namespace Ui
QT_END_NAMESPACE
This is widget.h:
#include <QtCore/qglobal.h>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
private:
Ui::Widget *ui;
};
This is widget.cpp:
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent), ui(new Ui::Widget) { ui->setupUi(this); }
Widget::~Widget() { delete ui; }
Sorry for adding the whole generated code but it might be helpful, Thanks.



QWidgetdoesn't support background images. TryQFrameinstead. - G.M.background, andbackground-imageis explicitly mentioned. If it doesn't work withQFrameas well I would check whether the image has been added to the Qt resources correctly and whether the path is correct. - Scheff's Cat