QMainWindow不显示Qwidgets背景

时间:2015-07-04 11:08:26

标签: c++ qt qwidget qmainwindow

我在QWidget(自定义制作)中遇到QMainWindow(自定义制作)的问题。我的问题是,当我使用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();
}

任何人都可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

检查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);
}