QWebEnginePage: toHtml returns an empty string

馋奶兔 提交于 2020-01-02 17:01:27

问题


I need to retrieve some html from a QWebEnginePage. I found in the documentation the method toHtml but it always returns an empty string. I tried toPlainText and it works, but this is not what I need.

MyClass::MyClass(QObject *parent) : QObject(parent)
{
   _wp = new QWebEnginePage();
   _wp->settings()->setAttribute(QWebEngineSettings::AutoLoadImages, false);
   _wp->settings()->setAttribute(QWebEngineSettings::JavascriptEnabled, true);
   connect(_wp, SIGNAL(loadFinished(bool)), this, SLOT(wpLoadFinished(bool)));
}
void MyClass::start()
{
   _wp->load(QUrl("http://google.com/"));
}
void MyClass::wpLoadFinished(bool s)
{
   _wp->toHtml(
       [] (const QString &result) {
          qDebug()<<"html:";
          qDebug()<<result;
    }); // return empty string
    /*_wp->toPlainText(
       [] (const QString &result) {
          qDebug()<<"txt:";
          qDebug()<<result;
    });*/ //works perfectly
}

What am I doing wrong?


回答1:


I am getting my head around QWebEngine. It is very cool. I have got the following to work.

The lambada capture needs to be all that is "=", or "this" in the case of signal being emitted. You would also need "mutable" to modify the captured copies. toHtml() is however asynchronous so even if you capture the html it is unlikely it would be available directly after the call to toHtml() in SomeFunction. You can overcome this by using a signal and slot.

protected slots:
    void handleHtml(QString sHtml);

signals:
    void html(QString sHtml);



 void MainWindow::SomeFunction()
 {
    connect(this, SIGNAL(html(QString)), this, SLOT(handleHtml(QString)));
    view->page()->toHtml([this](const QString& result) mutable {emit html(result);});
 }

void MainWindow::handleHtml(QString sHtml)
{
      qDebug()<<"myhtml"<< sHtml;
}



回答2:


I think that the problem is more a connection problem. Your code works fine on my appli :

    connect(page, SIGNAL(loadFinished(bool)), this,   SLOT(pageLoadFinished(bool)));

...

    page->load(QUrl("http://google.com/"));

...loading time...

 void MaClasse :: pageLoadFinished(bool s){
   page->toHtml([this](const QString &result){         
   qDebug()<<"html:";
   qDebug()<<result;
   item->setHtml(result);});
}


来源:https://stackoverflow.com/questions/36680604/qwebenginepage-tohtml-returns-an-empty-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!