QMainWindow不显示Qwidgets背景

QMainWindow does not show Qwidgets background

本文关键字:背景 Qwidgets 显示 QMainWindow      更新时间:2023-10-16

我在QMainWindow(自定义(中遇到了一个关于QWidget(自定义(的问题。我的问题是,当我使用setCentralWidget()方法将我的小部件添加到窗口作为它的中心小部件时,它不会显示小部件的背景。正确显示背景很重要。这是我的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();
}

有人能帮我解决这个问题吗??

检查这个答案。

我建议您使用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);
}