很简单,用QQuickImageProvider这个类。下面贴代码。
环境QT5.9
项目使用Quick Controls 2Application
项目比较简单。就不多做介绍了。注意头文件的使用。
头文件img.h
#ifndef IMG_H
#define IMG_H
#include <QQuickImageProvider>
#include<QImage>
#include<QTcpSocket>
#include <QTcpServer>
#include<QBuffer>
class ImageProvider : public QQuickImageProvider
{
public:
ImageProvider();
QImage requestImage(const QString &id, QSize *size, const QSize &requestedSize);
QPixmap requestPixmap(const QString &id, QSize *size, const QSize &requestedSize);
QImage img;
};
class ShowImage : public QObject
{
Q_OBJECT
public:
explicit ShowImage(QObject *parent = 0);
ImageProvider *m_pImgProvider;
public slots:
void sendimage(QImage);
signals:
void callQmlRefeshImg();
void sendPic(QImage image);
};
#endif // IMG_H
main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include "img.h"
#include <QQmlContext>
#include <QtWidgets/QApplication>
#include <QScreen>
#include <QtWidgets/QWidget>
#include <QImage>
ImageProvider::ImageProvider()
: QQuickImageProvider(QQuickImageProvider::Image)
{
}
QImage ImageProvider::requestImage(const QString &id, QSize *size, const QSize &requestedSize)
{
return this->img;
}
QPixmap ImageProvider::requestPixmap(const QString &id, QSize *size, const QSize &requestedSize)
{
return QPixmap::fromImage(this->img);
}
ShowImage::ShowImage(QObject *parent) :
QObject(parent)
{
m_pImgProvider = new ImageProvider();
}
void ShowImage::sendimage(QImage sendimage)
{
m_pImgProvider->img =sendimage ;
emit callQmlRefeshImg(); //告诉qml刷新一下。
}
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv); //注意qapplication qguiapplication
QQmlApplicationEngine engine;
ShowImage *CodeImage=new ShowImage();
engine.rootContext()->setContextProperty("CodeImage",CodeImage);
engine.addImageProvider(QLatin1String("CodeImg"),CodeImage->m_pImgProvider);
engine.load(QUrl(QLatin1String("qrc:/main.qml")));
QImage image;
image.load("d:\\q.jpg"); //载入
CodeImage->sendimage(image);//发送
if (engine.rootObjects().isEmpty())
return -1;
return app.exec();
}
targrt:Codeimage就是
engine.rootContext()->setContextProperty("CodeImage",CodeImage);
这句话注册的。
值得提醒的是。
onCallQmlRefeshImg:这里,我在c++里开头首字母写的是小写,这里用大写是可以的,但是如果c++函数那里写的是大写,qml这里不管你是小写还是大写都报错。官方文档里只是写了on<singel>,没说大小写。很奇怪。反正就是c++那里首字母小写,qml里大写就对了。
main.qml:
import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.3
ApplicationWindow {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Image
{
id:img
anchors.fill: parent
}
Connections{
target: CodeImage; //on{singal}: {//}
onCallQmlRefeshImg:
{
img.source =""
img.source = "image://CodeImg"
}
}
}
最终效果