第一步:重写QQuickImageProvider类
#include <QQuickImageProvider>
class CQuickImagePainter : public QQuickImageProvider
{
public:
CQuickImagePainter();
QImage requestImage(const QString&id, QSize *, const QSize &);
QPixmap requestPixmap(const QString&id, QSize *, const QSize &);
public:
QImage img;
};
#include "CQuickImagePainter.h"
CQuickImagePainter::CQuickImagePainter(): QQuickImageProvider(QQuickImageProvider::Image)
{
}
QImage CQuickImagePainter::requestImage(const QString&id, QSize*, const QSize&)
{
return this->img;
}
QPixmap CQuickImagePainter::requestPixmap(const QString&id, QSize*, const QSize&)
{
return QPixmap::fromImage(this->img);
}
第二步:定义刷新图像的类
#include <QObject>
#include <CQuickImagePainter.h>
class CQuickImageRefresh : public QObject
{
Q_OBJECT
public:
explicit CQuickImageRefresh(QObject *parent = nullptr);
CQuickImagePainter*m_RePainter;
signals:
void reDrawImage();
public slots:
void setImage(QImage image);
};
#include "CQuickImageRefresh.h"
CQuickImageRefresh::CQuickImageRefresh(QObject *parent) : QObject(parent)
{
m_RePainter = new CQuickImagePainter;
}
void CQuickImageRefresh::setImage(QImage image)
{
m_RePainter->img = image;
emit reDrawImage();
}
第三步:关联qml
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "CQuickImageRefresh.h"
//设置为全局变量-可以在线程中更新图像
CQuickImageRefresh *CodeImage1 = new CQuickImageRefresh();
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
const QUrl url(QStringLiteral("qrc:/main.qml"));
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
&app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
}, Qt::QueuedConnection);
engine.load(url);
//管理qml
engine.rootContext()->setContextProperty("CodeImage1",CodeImage1);
engine.addImageProvider(QLatin1String("CodeImg1"), CodeImage1->m_RePainter);
//每次CodeImage1->setImage(image)的时候界面自动刷新
QImage image = QImage(data,width,height,QImage::Format_RGB888);
CodeImage1->setImage(image);
return app.exec();
}
第四步:qml显示
import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.12
Window {
width: 640
height: 320
visible: true
title: qsTr("Hello World")
Image{
id:img1
width: 640
height: 360
x:0
y:0
}
Connections{
target: CodeImage1
onReDrawImage:{
img1.source = ""
img1.source = "image://CodeImg1"
}
}
}