您好,我是 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
:
- 创建一个
QPixmap
并为它提供您的图像的路径。 - 创建一个
QPalette
并使用您的像素图将其设置为QBrush
并将其ColorRole
设置为QPalette::Background
。 - 将您的
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/