Sijith
Sijith

Reputation: 3960

Background image not showing on QWidget

I am designing a window using QWidget and set a background image, when i run my code i am not getting background image but showing window with default background.

Can anyone help me what may 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);
}

Upvotes: 2

Views: 8238

Answers (2)

Bernat
Bernat

Reputation: 11

You can reimplement paintEvent:

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

    QWidget::paintEvent( e );
}

Upvotes: 1

Naruto
Naruto

Reputation: 9634

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

I will give you one simple technique. i.e Override, the paintEvent of the QWidget. and draw the pixmap there.

Here is the 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);
}

Upvotes: 3

Related Questions