我正在使用loadHtml
方法将HTML内容注入QML WebEngineView,我试图让它通过QQuickImageProvider加载图像。
到目前为止,我们已成功从Qt资源容器(qrc)加载图像,但这还不够灵活。
contentimageprovider.cpp
#include "contentimageprovider.h"
#include <QDebug>
ContentImageProvider::ContentImageProvider() : QQuickImageProvider(QQuickAsyncImageProvider::Image)
{
}
QImage ContentImageProvider::requestImage(const QString &id, QSize *size, const QSize &requestedSize)
{
qDebug() << __FUNCTION__ << id;
}
的main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QtWebEngine/QtWebEngine>
#include "contentimageprovider.h"
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
QtWebEngine::initialize();
engine.addImageProvider(QLatin1String("content-images"), new ContentImageProvider);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
main.qml
import QtQuick 2.7
import QtQuick.Window 2.2
import QtWebEngine 1.4
Image {
source: "image://content-images/this-image-is-requested";
}
WebEngineView {
Component.onCompleted: {
loadHtml("<img src='qrc://images/this-image-is-displayed.png' /><img src='image://content-images/this-image-should-also-be-requested' />", "/");
}
}
预期输出
requestImage "this-image-is-requested"
requestImage "this-image-should-also-be-requested"
实际输出
requestImage "this-image-is-requested"
显示通过WebEngineView中的qrc加载的图像,并显示另一个图像的损坏图像。
有没有人能够让这个工作?
答案 0 :(得分:0)
感谢@Xplatforms指出了初步错误,假设QML WebEngineView下的Chromium引擎会与QML Quick引擎交互并触发图像提供程序。
解决方案是实现 QWebEngineUrlSchemeHandler :
void ImageRequestHandler::requestStarted(QWebEngineUrlRequestJob *request)
{
// request->requestUrl() is a QUrl
QFile *image = new QFile(QDir::currentPath() + "/storage/content/" + request->requestUrl().path() + ".png");
// makes sure the image deletes itself when closing the file
connect(image, &QIODevice::aboutToClose, image, &QObject::deleteLater);
// close the file when the request job is done
connect(request, &QObject::destroyed, image, &QIODevice::close);
QMimeDatabase mimeDB;
QMimeType mimeType = mimeDB.mimeTypeForFile(image->fileName());
request->reply(mimeType.name().toUtf8(), image);
}
<强>的main.cpp 强>
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
// web engine to provide content display
QtWebEngine::initialize();
// intercept requests from the web engine to provide locally loaded content and images
ImageRequestHandler *imageRequestHandler = new ImageRequestHandler();
QQuickWebEngineProfile::defaultProfile()->installUrlSchemeHandler("image", imageRequestHandler);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}