使用 QPixmap 和 QLabel 在 Qt Creator 中以编程方式添加图像文件 (.PNG)

Adding an image file (.PNG) programatically in Qt Creator using QPixmap and QLabel

大家早上好,

我在使用 QPixmap 和 QLabel 方法将 .PNG 文件添加到我的 Qt Creator 项目时遇到问题。下面显示了我尝试执行此操作的不同方法(以代码片段格式)。

系统:Raspberry Pi2运行Debian Wheezy
生成器:嵌入式 Qt 版本 4.8.2 Linux
Compiler/Tool链:GCC/G++ 4.9.2

code snippet 1
1 #include <QtGui/QApplication>
2 #include <QPixmap>
3 #include <QLabel>
4 #include <wiringPi.h>
5 #include "mainwindow.h"
...
187 QLabel myLabelPi;
188 QPixmap myPixmapPi = new QPixmap(":/GPIOGUI/rpi2.png");
189 myLabelPi.setPixmap(myPixmapPi);
190 myLabelPi.setScaledContents(true);
191 myLabelPi.show();

code snippet 2
1 #include <QtGui/QApplication>
2 #include <QPixmap>
3 #include <QLabel>
4 #include <wiringPi.h>
5 #include "mainwindow.h"
...        
187 QLabel myLabelPi;
188 QPixmap *myPixmapPi = new QPixmap(":/GPIOGUI/rpi2.png");
189 myLabelPi.setPixmap(myPixmapPi);
190 myLabelPi.setScaledContents(true);
191 myLabelPi.show();

这些代码在编译时(分别)出现的错误是:

代码片段 1:
/home/pi/gpioGUI/main.cpp:187: 错误:请求从 'QPixmap*' 到非标量类型 'QPixmap' 的转换

代码片段 2:
/home/pi/gpioGUI/main.cpp:188: 错误:没有匹配函数来调用 'QLabel::setPixmap(QPixmap*&)' 候选人是: void QLabel::setPixmap(const QPixmap&) 注意:参数 1 没有从 'QPixmap*' 到 'const QPixmap&'

的已知转换

非常感谢您提供的任何帮助。

仔细阅读错误,大多数时候它包含错误。

第 188 行:new returns 一个指针。因此你的变量应该是一个指针(带有 *

QPixmap* myPixmapPi = new QPixmap(":/GPIOGUI/rpi2.png");

第189行,也说出了什么问题。您正在传递一个需要引用的指针。 (虽然我还没有测试代码)

myLabelPi.setPixmap(*myPixmapPi);

试试看。