Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add a background image to the QMainWindow?

Tags:

c++

qt

Hi I am new to QT creator. I have tried a bunch of things to set my background image for the Q mainwindow. I added a resource folder with my image. I tried to add the by using setstylesheet in the UI and tried coding it. When I use the UI I can see the image, but when I run it nothing shows. I want put an image of a poker table that I have as the background and be able to put pushbuttons, etc on top.

main.cpp:

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();


    return a.exec();
}

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setStyleSheet("{background-image: url(:/images/images/PokerTableBackground.jpg);}");
}

MainWindow::~MainWindow()
{
    delete ui;
}

Like I said I tried doing this, and putting the image through the UI and neither one of them work. I want the image set as the background for the whole thing.

I also tried using this:

QWidget *pic = new QWidget(ui->tab);
    pic->setStyleSheet("background-image: url(:/images/images/PokerTableBackground.jpg)");
    pic->setGeometry(QRect(10,10,220,48)); // your location and size.
like image 304
Sahil Gupta Avatar asked Nov 12 '13 21:11

Sahil Gupta


1 Answers

You can add a background image to your MainWindow by doing the following:

  1. create a QPixmap and give it the path to your image.
  2. create a QPalette and set it's QBrush with your pixmap and it's ColorRole to QPalette::Background.
  3. set your MainWindow palette to the palette you created.

as an example you can add this lines to the constructor of your MainWindow class:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QPixmap bkgnd("/home/user/Pictures/background.png");
    bkgnd = bkgnd.scaled(this->size(), Qt::IgnoreAspectRatio);
    QPalette palette;
    palette.setBrush(QPalette::Background, bkgnd);
    this->setPalette(palette);
}

the advantage with this one is that you have the ability of modifying/changing your background image programmatically without having to use or learn any css stylesheet syntaxes.

like image 70
moki Avatar answered Oct 01 '22 19:10

moki