C++ 如何在 QT 框架的 UI 上显示“*.png”文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6910946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 20:52:09  来源:igfitidea点击:

How to Display a "*.png" file on a UI in QT framework?

c++qtuser-interfacepng

提问by karim

I am new to Qt Framework...

我是 Qt 框架的新手...

I want to display a .png pic in my Form1.ui , so I dragged and dropped a Graphic view from the widget box then I placed test.png in the same directory (inside the project folder)

我想在我的 Form1.ui 中显示一个 .png 图片,所以我从小部件框中拖放了一个图形视图,然后我将 test.png 放在同一目录中(在项目文件夹内)

and i did this in the code

我在代码中做了这个

//Form1.cpp
#include "form1.h"
#include "ui_form1.h"

Form1::Form1(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Form1)
{
    ui->setupUi(this);
    ui->Pic1->setStyleSheet("background-image: url(test.png)");

}

Form1::~Form1()
{
    delete ui;
}



//Form1.h
#ifndef FORM1_H
#define FORM1_H

#include <QWidget>

namespace Ui {
    class Form1;
}

class Form1 : public QWidget
{
    Q_OBJECT

public:
    explicit Form1(QWidget *parent = 0);
    ~Form1();

private:
    Ui::Form1 *ui;
};

#endif // FORM1_H

It compiled perfectly but the pic didn't appear , What did I Wrong ?

它编译完美,但图片没有出现,我做错了什么?

this is my qrc :

这是我的 qrc :

回答by Vinicius Kamakura

The Widget you should use to show pictures is a QLabel. You can do it directly from QtCreator, by setting its pixmapproperty.

您应该用来显示图片的小部件是一个QLabel. 您可以通过设置其pixmap属性直接从 QtCreator 执行此操作。

As others said, you should first create a resource file and then add the image to that resource file. To create a Qt Resource File, go to the menus: File > Qt > Qt Resource File.

正如其他人所说,您应该首先创建一个资源文件,然后将图像添加到该资源文件中。要创建 Qt 资源文件,请转到菜单:文件 > Qt > Qt 资源文件。

EDITTo do it programatically:

编辑以编程方式执行此操作:

//names starting with : means that they are on a resource file, 
//otherwise in the filesystem
QPixmap * mypix = new QPixmap(":/karim/test.png"); 
ui->your_label->setPixmap(mypix);
delete mypix;

回答by g_fred

You need to add the image to a resource file: http://doc.qt.io/qt-5/resources.html

您需要将图像添加到资源文件中:http: //doc.qt.io/qt-5/resources.html

回答by Pete

If you have the png in your resources, maybe change your background-image: tag:

如果您的资源中有 png,请更改您的 background-image: 标签:

ui->Pic1->setStyleSheet("background-image: url(:/test.png)");