QMainWindow 不显示 Qwidgets 背景

QMainWindow does not show Qwidgets background

我对 QMainWindow(定制)中的 QWidget(定制)有疑问。我的问题是,当我使用 setCentralWidget() 方法将我的小部件添加到我的 window 作为其中央小部件时,它不会显示小部件背景。正确显示背景很重要。 这是我的 MyWindow.cpp 代码:

#include "MyMainWindow.h"

MyMainWindow::MyMainWindow(QWidget * parent, Qt::WindowFlags flag) :
        QMainWindow(parent, flag)
{
    this->setFixedSize(1120, 630);
    menu = new MyMenu(this);
//    setting = new MySetting();
//    tutorial = new MyTutorial();
//    game = new MyGame();
    this->setCentralWidget(menu);
    this->show();
}

MyMainWindow::~MyMainWindow()
{
}

我的MyMenu.cpp代码:

#include "MyMenu.h"

MyMenu::MyMenu(QWidget *parent, Qt::WindowFlags f) :
        QWidget(parent, f)
{
    this->resize(1120, 630);
    this->set_background();
    this->construct_buttons();
    this->construct_menu();
}

MyMenu::~MyMenu()
{
    delete start;
    delete setting;
    delete tutorial;
    delete exit;
    delete buttons;
    delete logo;
    delete menu;
}

void MyMenu::construct_menu()
{
    menu = new QVBoxLayout(this);
    logo = new QLabel(this);
    QPixmap *pixmap = new QPixmap("/home/kahrabian/ClionProjects/Shooter-AP93UT/Contents/logo.png");
    logo->setPixmap(*pixmap);
    logo->setAlignment(Qt::AlignHCenter);
    menu->addWidget(logo);
    menu->addLayout(buttons);
    delete pixmap;
}

void MyMenu::construct_buttons()
{
    buttons = new QHBoxLayout();
    start = new QPushButton("Start", this);
    buttons->addWidget(start);
    setting = new QPushButton("Setting", this);
    buttons->addWidget(setting);
    tutorial = new QPushButton("Tutorial", this);
    buttons->addWidget(tutorial);
    exit = new QPushButton("Exit", this);
    buttons->addWidget(exit);
}

void MyMenu::set_background()
{
    QPalette *palette = new QPalette();
    palette->setBrush(this->backgroundRole(),QBrush(QImage("/home/kahrabian/ClionProjects/Shooter-AP93UT/Contents/background_menu.jpg")));
    this->setPalette(*palette);
    delete palette;
}

我的main.cpp代码:

#include <QApplication>
#include "MyMenu.h"
#include "MyMainWindow.h"

int main(int argc, char **argv)
{
    QApplication app (argc, argv);
    MyMainWindow *mainwin = new MyMainWindow();
//    MyMenu *MyMenu = new MyMenu();
//    MyMenu->show();
    return app.exec();
}

谁能帮我解决这个问题??

检查this answer

我建议您使用 Qt 样式表。

你需要这样调用:

setStyleSheet("image: url(path/to/background/image.png);");

在您的小部件上。

此外,您可能需要实施 paintEvent() 让小部件接受样式表。
我通常这样做:

void MyWidget::paintEvent(QPaintEvent *pe)
{    
    QStyleOption opt;
    opt.init(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);

    QWidget::paintEvent(pe);
}