1.定义一个ColorImageProvider类
#ifndef COLORIMAGEPROVIDER_H
#define COLORIMAGEPROVIDER_H
#include <QObject>
#include <QImage>
#include <QQuickImageProvider>
#include <QTimer>
class ColorImageProvider :public QObject, public QQuickImageProvider
{
Q_OBJECT
public:
ColorImageProvider(QObject* parent = nullptr)
: QQuickImageProvider(QQuickImageProvider::Image)
{
connect(&_timer, &QTimer::timeout, this, [this](){
int width = 100;
int height = 50;
static int n = 0;
n++;
QPixmap pixmap( width,
height);
if( n % 2 == 0)
pixmap.fill(QColor("blue").rgba());
else
pixmap.fill(QColor("green").rgba());
setImage(pixmap.toImage());
});
}
QImage requestImage(const QString& id, QSize* size, const QSize& requestedSize) override
{
if(size) *size = _image.size();
if(requestedSize.width() > 0 && requestedSize.height() > 0 ){
return _image.scaled(requestedSize.width(), requestedSize.height(), Qt::KeepAspectRatio);
}
return _image;
}
void start(int ms){
_timer.start(ms);
}
signals:
void imageUpdated();
private:
QTimer _timer;
QImage _image;
void setImage(const QImage& image){
if(!image.isNull()){
_image = image;
emit imageUpdated();
}
}
};
#endif // COLORIMAGEPROVIDER_H
2.main.cpp 注册并定时显示
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include "ColorImageProvider.h"
#include <QQmlContext>
int main(int argc, char *argv[])
{
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
ColorImageProvider* provider = new ColorImageProvider();
engine.rootContext()->setContextProperty("imageProvider", provider);
engine.addImageProvider(QLatin1String("stream"), provider);
provider->start(1000);
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);
return app.exec();
}
3.在main.qml中添加控件
import QtQuick 2.15
import QtQuick.Window 2.15
Window {
width: 640
height: 480
visible: true
title: qsTr("Hello World")
Connections {
target: imageProvider
function onImageUpdated() {
image1.reload()
}
}
Column {
Image {
id: image1
readonly property string providerSource: "image://stream/";
fillMode: Image.PreserveAspectFit
asynchronous: false
cache: false
function reload() {
var oldSource = providerSource;
console.log(oldSource)
source = "";
source = oldSource;
}
}
}
}
4.执行效果