【问题标题】:Qt - draw pixmap (.png file) with QPainter from resourcesQt - 从资源中使用 QPainter 绘制像素图(.png 文件)
【发布时间】:2015-04-01 15:51:47
【问题描述】:

我在使用资源中的 QPainter 在 QWidget 上绘制图像时遇到了一些问题。我确定我错过了一些东西,但我真的不知道是什么。如果我使用绝对路径,它工作正常。

所以我的问题是:如果我想用 QPainter 从资源中绘制 .png 文件该怎么办? (我错过了什么?)

这是我的简单测试代码:

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 文件:

<RCC>
    <qresource prefix="/img">
        <file>image.png</file>
    </qresource>
</RCC>

和 .pro 文件:

#-------------------------------------------------
#
# 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

【问题讨论】:

  • 我可以看到pixmap1pixmap2。你的窗户够大吗?
  • 是的,它是..我认为默认 cca 500x500
  • 你能把你的整个项目发给我吗?
  • pixmap2 来自已编译资源。你清理项目了吗?

标签: qt resources draw qpainter qpixmap


【解决方案1】:

正如我所料,这真是个愚蠢的问题。我所要做的就是清理项目,运行 qmake 并构建...感谢 svlasov :)

编辑: 因此,为了从资源中使用 QPainter 和 QPixmap 绘制 .png 文件,您必须: 将您的图片添加到资源中

<RCC>
    <qresource prefix="/img">
        <file>image.png</file>
    </qresource>
</RCC>

然后您可以在此处的资源中使用文件的相对路径(格式为“:/prefix/you/created/file.something”,或者您可以使用别名 - 这里是documentation

QPixmap pixmap2(":/img/image.png");

然后画出来

QPainter painter(this);
painter.drawPixmap(10,70,50,50, pixmap2);

清理和构建项目,它会工作:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-07
    • 2020-05-11
    相关资源
    最近更新 更多