如何将QPixmap添加到QWebEngineView

时间:2019-07-25 06:53:38

标签: qt

我正在以QString动态创建html页面并将其设置为QWebEngineView, 对于静态资源映像,我没有问题,我可以这样做:

    html += "<img src='qrc:/img/logo.png'/>"

但是对于动态准备好的QPixmap如何插入呢?

1 个答案:

答案 0 :(得分:0)

一种可能的解决方案是将其转换为base64:

#include <QApplication>
#include <QWebEngineView>
#include <QBuffer>

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QApplication app(argc, argv);

    QWebEngineView view;

    QPixmap pixmap(512, 512);
    pixmap.fill(QColor("salmon"));

    // to bytes
    QByteArray bytes;
    QBuffer buffer(&bytes);
    buffer.open(QIODevice::WriteOnly);
    pixmap.save(&buffer, "PNG");
    // to base64
    QByteArray ba = bytes.toBase64();

    QString html;
    html += QString("<img src='data:image/png;base64,%1'/>").arg(QString(ba));
    view.setHtml(html);
    view.resize(1024, 750);
    view.show();

    return app.exec();
}