How do I add a background image to the QMainWindow?

后端 未结 3 2006
被撕碎了的回忆
被撕碎了的回忆 2020-12-03 15:05

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 usi

相关标签:
3条回答
  • 2020-12-03 15:53

    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.

    0 讨论(0)
  • 2020-12-03 15:54

    You can set background style sheet of central window,

    this->centralWidget()->setStyleSheet("background-image:url(\"bkg.jpg\"); background-position: center; ");
    

    In the constructor it would be something like this:

    MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
    
        this->centralWidget()->setStyleSheet(
             "background-image:url(\"bkg.jpg\"); background-position: center;" );
    }
    
    0 讨论(0)
  • 2020-12-03 16:01

    The CSS style background will be inherited in the child widgets and thus create weird looking windows. A possible solution is to limit the background to MainWindow or #centralWidget. If, additionally, you want to stretch the image to cover the full widget, use this kind of CSS

    this->setStyleSheet(
                "#centralWidget { "
                " border-image: url(:/background.png) 0 0 0 0 stretch stretch;"
                "}");
    
    0 讨论(0)
提交回复
热议问题