c++ - 如何向 QMainWindow 添加背景图像?

标签 c++ qt

您好,我是 QT Creator 的新手。我尝试了很多方法来为 Q 主窗口设置背景图像。我用我的图像添加了一个资源文件夹。我尝试通过在 UI 中使用 setstylesheet 添加并尝试对其进行编码。当我使用 UI 时,我可以看到图像,但是当我运行它时什么也没有显示。我想放一张扑克牌 table 的图片作为背景,并能够在顶部放置按钮等。

主要.cpp:

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

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


    return a.exec();
}

主窗口.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;
}

就像我说的那样,我尝试这样做,并通过 UI 放置图像,但两者都不起作用。我想要将图像设置为整个事物的背景。

我也试过用这个:

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.

最佳答案

您可以通过执行以下操作将背景图像添加到您的 MainWindow:

  1. 创建一个 QPixmap 并为它提供您的图像的路径。
  2. 创建一个 QPalette 并使用您的像素图将其设置为 QBrush 并将其 ColorRole 设置为 QPalette::Background
  3. 将您的 MainWindow 调色板设置为您创建的调色板。

例如,您可以将此行添加到 MainWindow 类的构造函数中:

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

这个的优点是您能够以编程方式修改/更改背景图像,而无需使用或学习任何 css 样式表语法。

关于c++ - 如何向 QMainWindow 添加背景图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19939938/

相关文章:

c++ - 我可以在头文件中#define QStringLiterals 吗?

python - pyqt4:如何查看QWebPage?

c++ - 生成一定范围内的 float 序列

c++ - 两个整数到一个 double C++

c++ - 定义非 constexpr 大小的数组时没有错误

c++ - Swift、C++ 和结构

c++ - 编译 Qt 教程时出现 "undefined symbols for architecture"链接器错误

c++ - 在多核机器上使用 boost asio 只有 1 个线程

qt - 如何设置 Qt 应用程序在哪里找到 Qt 模块?

qt - QVariant 内部如何工作?