Reputation: 330
I have some problems with drawing image on QWidget with QPainter from resources. I'm sure I'm missing something but I really dont know what. If I use absolute path, it works fine.
So my question is: what should I do if I want to draw .png file from resources with QPainter? (What am I missing?)
Here is my simple test code:
Widget.h:
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QPaintEvent>
#include <QPixmap>
#include <QPainter>
class Widget : public QWidget {
Q_OBJECT
public:
Widget(QWidget *parent = 0);
protected:
void paintEvent(QPaintEvent* e);
};
#endif // WIDGET_H
Widget.cpp:
#include "Widget.h"
Widget::Widget(QWidget *parent): QWidget(parent) { }
void Widget::paintEvent(QPaintEvent *e) {
QPainter painter(this);
QPixmap pixmap1("C:/Qt/Projects/pixmapTest/image.png");
QPixmap pixmap2(":/img/image.png");
QPixmap pixmap3("qrc:/img/image.png");
painter.drawPixmap(10,10,50,50, pixmap1); // this works
painter.drawPixmap(10,70,50,50, pixmap2); // this not
painter.drawPixmap(10,130,50,50, pixmap3); // this neither
}
img.qrc file:
<RCC>
<qresource prefix="/img">
<file>image.png</file>
</qresource>
</RCC>
and .pro file:
#-------------------------------------------------
#
# Project created by QtCreator 2015-04-01T17:11:38
#
#-------------------------------------------------
QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = pixmapTest
TEMPLATE = app
SOURCES += main.cpp\
Widget.cpp
HEADERS += Widget.h
FORMS +=
RESOURCES += \
img.qrc
Upvotes: 1
Views: 26486
Reputation: 330
As I expected, it was really stupid problem. All i had to do was clean project, run qmake and build... Thanks to svlasov :)
Edit: So in order to draw .png file with QPainter and QPixmap from resources, you have to: add your picture to resources
<RCC>
<qresource prefix="/img">
<file>image.png</file>
</qresource>
</RCC>
then you can use relative path to your file in resources like here (format is ":/prefix/you/created/file.something" or you can use alias - here is documentation)
QPixmap pixmap2(":/img/image.png");
then draw it
QPainter painter(this);
painter.drawPixmap(10,70,50,50, pixmap2);
and clean and build project and it will work :)
Upvotes: 9