한국어
Qt

애플리케이션이 시작될 때 Qt 리소스에서 Qml을 로드하는 경우, Qml뿐만 아니라 모든 이미지는 Qt리소스에서 로드된다.

로컬이나 네트웍 같은 곳에서 이미지를 로드해야 할 필요가 있을 경우 Image Provider를 사용하면 된다.


imageprovider.h

 #ifndef IMAGEPROVIDER_H
#define IMAGEPROVIDER_H

#include <QQuickImageProvider>

class ImageProvider : public QObject, public QQuickImageProvider
{
   Q_OBJECT
  public:

   ImageProvider();
   ~ImageProvider();
   static ImageProvider * instance();
   QImage requestImage(const QString& id, QSize* size, const QSize& requestedSize);
   QPixmap requestPixmap(const QString& id, QSize* size, const QSize& requestedSize);
};

#endif // IMAGEPROVIDER_H


imageprovider.cpp

 #include "imageProvider.h"
#include <QFile>
#include <QImage>
#include <QPixmap>
#include <QDebug>

ImageProvider *ImageProviderInstance;

ImageProvider::ImageProvider()
    :QQuickImageProvider(QQmlImageProviderBase::Image)
{

}

ImageProvider::~ImageProvider()
{

}

ImageProvider *ImageProvider::instance()
{
    if(ImageProviderInstance)
    {
        return ImageProviderInstance;
    }
    else
    {
        ImageProviderInstance = new ImageProvider;
        return ImageProviderInstance;
    }
}

QImage ImageProvider::requestImage(const QString& id, QSize* size, const QSize&    requestedSize)
{
    QImage image(id);
    QImage result;

    if (requestedSize.isValid()) {
        result = image.scaled(requestedSize, Qt::KeepAspectRatio);
    } else {
         result = image;
    }
    *size = result.size();
    return result;
}

 QPixmap ImageProvider::requestPixmap(const QString& id, QSize* size, const QSize& requestedSize)
 {
    QPixmap image(id);
    QPixmap result;

    if (requestedSize.isValid()) {
        result = image.scaled(requestedSize, Qt::KeepAspectRatio);
    } else {
    result = image;
    }
    *size = result.size();
    return result;
}


mainwindow.cpp 에 imageprovider객체 등록

 context->engine()->addImageProvider(QString("extern"), ImageProvider::instance());

Qml 애플리케이션

 Image {
    id: img
    x: 0
    y: 25
    width: 227
    height: 230
    anchors.horizontalCenter: parent.horizontalCenter
     source: "image://extern/"+path
    //doesn't find absolute path in windows source: "file://"+path
    fillMode: Image.PreserveAspectFit
}


참고: http://stackoverflow.com/questions/15865846/error-while-set-up-absolute-image-path-in-qml-qt-under-windows