微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

QWebEngineView setHtml不更新html并将其留空

如何解决QWebEngineView setHtml不更新html并将其留空

我正在尝试从随机HTML中打印出png图像。但是,每当我调用QWebEngineView::setHtml时,信号QWebEngine::loadFinished都会被正确触发,但是html从未设置。我尝试在下面创建一个最低版本:

//main.cpp

QApplication app(argc,argv);

const QString html = "<!DOCTYPE html><html><body><div><h1>Title</h1><p style=\"background-color:red;\">Some Text</p></div></body></html>";

DomCleaner cleaner(&app);
QObject::connect(&cleaner,&DomCleaner::finished,&app,&QApplication::quit);

cleaner.clean(html,QSize(800,800));

return app.exec();

我班的头

//domcleaner.h

//nevermind the name,it is because in the future I will do dom manipulation
class DomCleaner : public QObject
{
    Q_OBJECT

private:
    std::unique_ptr<QGraphicsScene> scene_;
    std::unique_ptr<QWebEngineView> view_;
    QImage image_;

public:
    explicit DomCleaner(QObject *parent = nullptr);

private:
    void traverseItem(QGraphicsItem *item);

public slots:
    void clean(const QString& html,QSize size);

private slots:
    void onHtmlLoaded();

signals:
    void finished();
};

最后,该类的定义

//domcleaner.cpp

DomCleaner::DomCleaner(QObject *parent) : QObject(parent)
{
    scene_.reset(new QGraphicsScene());
    view_.reset(new QWebEngineView());

    scene_->addWidget(view_.get());

    QObject::connect(view_.get(),&QWebEngineView::loadFinished,this,&DomCleaner::onHtmlLoaded);
}

void DomCleaner::clean(const QString& html,QSize size)
{
    image_ = QImage(size,QImage::Format_ARGB32);

    view_->resize(size);
    view_->setHtml(html);
    //this one is working
    //view_.get()->load(QUrl("https://doc.qt.io/qt-5/qgraphicsitem.html"));

    view_.get()->show();
}

void DomCleaner::onHtmlLoaded()
{
    QPainter painter(&image_);
    view_->render(&painter);
    painter.end();

    // prints an empty string
    view_->page()->toHtml([](QString html){ std::cout << html.toStdString() << std::endl; });

    image_.save("C:\\path\\to\\file\\test.png","PNG");

    emit finished();
}

使用html字符串调用QWebEngineView::setHtml时,将呈现白色图像,并且html为空。但是,当使用QWebEngineView::load从网址加载html时,一切正常。

我是否误解了如何使用QWebEngineView::setHtml?从文档看来,从用户的角度来看,这两个功能应该以相同的方式工作。此外,在调用QWebEngineView::setHtml之后,信号会正确发出。

注意:我在Windows 10计算机上将Qt 5.15.1与MSVC 2019 64位一起使用。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。