Kokos34
Kokos34

Reputation: 67

Background in Qt multiplies instead of fitting into window size

As in title, I was trying to make the background image resize to the window size using the following code:

QPixmap bkgnd(":/new/prefix1/bkgrnd.png");
bkgnd = bkgnd.scaled(this->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);

QPalette palette;

palette.setBrush(QPalette::Background, bkgnd);
this->setPalette(palette);

But the image gets multiplied and pasted next to each other instead of resizing to window size.

Original size window Resized image

Upvotes: 0

Views: 612

Answers (1)

sddk
sddk

Reputation: 1115

If you want the image to always fit to form, you should write your code in resize event of widget. To do that, you should overrite the resize event of widget. Add this lines to *.hpp file

protected:
    void resizeEvent(QResizeEvent* evt) override;

and then, write your code in the resizeEvent method.

void MainWindow::resizeEvent(QResizeEvent* evt)
{
    QPixmap bkgnd(":/new/prefix1/bkgrnd.png");
    bkgnd = bkgnd.scaled(this->size(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);

    QPalette palette;

    palette.setBrush(QPalette::Background, bkgnd);
    this->setPalette(palette);

    QMainWindow::resizeEvent(evt); // call inherited implementation
}

to increase performance, do not create 'QPixmap bkgnd' in resize event.

Upvotes: 1

Related Questions