imageresponseprovider.cpp Example File
imageresponseprovider/imageresponseprovider.cpp
#include <qqmlextensionplugin.h>
#include <qqmlengine.h>
#include <qquickimageprovider.h>
#include <QDebug>
#include <QImage>
#include <QThreadPool>
class AsyncImageResponse : public QQuickImageResponse, public QRunnable
{
public:
AsyncImageResponse(const QString &id, const QSize &requestedSize)
: m_id(id), m_requestedSize(requestedSize)
{
setAutoDelete(false);
}
QQuickTextureFactory *textureFactory() const override
{
return QQuickTextureFactory::textureFactoryForImage(m_image);
}
void run() override
{
m_image = QImage(50, 50, QImage::Format_RGB32);
if (m_id == "slow") {
qDebug() << "Slow, red, sleeping for 5 seconds";
QThread::sleep(5);
m_image.fill(Qt::red);
} else {
qDebug() << "Fast, blue, sleeping for 1 second";
QThread::sleep(1);
m_image.fill(Qt::blue);
}
if (m_requestedSize.isValid())
m_image = m_image.scaled(m_requestedSize);
emit finished();
}
QString m_id;
QSize m_requestedSize;
QImage m_image;
};
class AsyncImageProvider : public QQuickAsyncImageProvider
{
public:
QQuickImageResponse *requestImageResponse(const QString &id, const QSize &requestedSize) override
{
AsyncImageResponse *response = new AsyncImageResponse(id, requestedSize);
pool.start(response);
return response;
}
private:
QThreadPool pool;
};
class ImageProviderExtensionPlugin : public QQmlExtensionPlugin
{
Q_OBJECT
Q_PLUGIN_METADATA(IID QQmlExtensionInterface_iid)
public:
void registerTypes(const char *uri) override
{
Q_UNUSED(uri);
}
void initializeEngine(QQmlEngine *engine, const char *uri) override
{
Q_UNUSED(uri);
engine->addImageProvider("async", new AsyncImageProvider);
}
};
#include "imageresponseprovider.moc"