Qt Qml 使用 QQuickImageProvider 加载图片(同步)

#pragma execution_character_set("utf-8")
#include 
#include 
#include 

class QNetworkAccessManager;

// 图片加载 同步

class ImageProvider : public QQuickImageProvider
{
public:
    ImageProvider(ImageType type, Flags flags = 0);

    ~ImageProvider();

    QImage requestImage(const QString &id, QSize *size, const QSize &requestedSize);

protected:
    QNetworkAccessManager *manager;
};

#include "ImageProvider.h"

#include 
#include 
#include 

ImageProvider::ImageProvider(ImageType type, Flags flags) : QQuickImageProvider(type, flags)
{
    manager = new QNetworkAccessManager;
}

ImageProvider::~ImageProvider()
{
    delete manager;
}

QImage ImageProvider::requestImage(const QString &id, QSize *size, const QSize &requestedSize)
{
    QUrl url(id);
    QNetworkReply *reply = manager->get(QNetworkRequest(url));
    QEventLoop eventLoop;
    QObject::connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
    eventLoop.exec();
    if (reply->error() != QNetworkReply::NoError) {
        QImage *img = new QImage();
        img->load("qrc:/images/image_default.png", "PNG");
        // 如果出现错误
        return *img;
    }
    QImage image = QImage::fromData(reply->readAll());
    size->setWidth(image.width());
    size->setHeight(image.height());
    return image;
}

你可能感兴趣的:(qt)