Background image not showing in QWidget

I create a window with QWidget

and set a background image, when I run my code, I don't get the background image, but show the window with a standard background.

Can anyone help me what might be the reason.


// In header file
class STUDY : public QMainWindow, public Ui::STUDYClass
{
    Q_OBJECT

public:
    STUDY(QWidget *parent = 0, Qt::WFlags flags = 0);
    ~STUDY();

    QPaintEvent *p2;

    void backgroundImage();
    void paintEvent(QPaintEvent *);

public slots:
};

//Constructor and paintEvent function in Cpp file

STUDY::STUDY(QWidget *parent, Qt::WFlags flags)
: QMainWindow(parent, flags)
{
    setupUi(this);
    backgroundImage();
    update();
    paintEvent(p2);
}

void STUDY::paintEvent(QPaintEvent *p2)
{
    QPixmap pixmap;
    pixmap.load(":/STUDY/Resources/Homepage.png");
    QPainter paint(this);
    paint.drawPixmap(0, 0, pixmap);
    QWidget::paintEvent(p2);
}

      

+2


a source to share


2 answers


There are many ways to set the background color of a window,

I will give you one simple method. ie override paintEvent

QWidget

. and draw a pixmap there.

Here is a sample widget code, I hope it helps

Header file



#ifndef QBACKGROUNDIMAGE_H
#define QBACKGROUNDIMAGE_H

#include <QtGui/QMainWindow>
#include "ui_QbackgroundImage.h"
#include <QtGui>

class backgroundImgWidget;

class QbackgroundImage : public QMainWindow
{
    Q_OBJECT

public:
    QbackgroundImage(QWidget *parent = 0);
    ~QbackgroundImage();

private:
    Ui::QbackgroundImage ui;
};

class backgroundImgWidget : public QWidget
{
     Q_OBJECT

public:
    backgroundImgWidget(QWidget *parent = 0);
    ~backgroundImgWidget();

protected:
    void paintEvent(QPaintEvent *p2);
};

#endif // QBACKGROUNDIMAGE_H

      

CPP file

#include "QbackgroundImage.h"

QbackgroundImage::QbackgroundImage(QWidget *parent)
    : QMainWindow(parent)
{
    // ui.setupUi(this);

    backgroundImgWidget* widget = new backgroundImgWidget();
    setCentralWidget(widget);
}

QbackgroundImage::~QbackgroundImage()
{
}

backgroundImgWidget::backgroundImgWidget(QWidget *parent):QWidget(parent)
{
}

backgroundImgWidget::~backgroundImgWidget()
{
}

void backgroundImgWidget::paintEvent(QPaintEvent *p2)
{
    QPixmap pixmap;

    pixmap.load(":/new/prefix1/Sunset.jpg");

    QPainter paint(this);
    paint.drawPixmap(0, 0, pixmap);
    QWidget::paintEvent(p2);
}

      

+3


a source


You can override paintEvent

:



void Widget::paintEvent( QPaintEvent* e )
{
    QPainter painter( this );
    painter.drawPixmap( 0, 0, QPixmap(":/new/prefix1/picture001.png").scaled(size()));

    QWidget::paintEvent( e );
}

      

0


a source







All Articles