QWebEnginePage:toHtml返回一个空字符串

时间:2016-04-17 18:38:01

标签: c++ qt qtwebengine

我需要从QWebEnginePage检索一些html。我在文档中找到了方法toHtml,但它总是返回一个空字符串。我试过toPlainText  它有效,但这不是我需要的。

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
}

我做错了什么?

2 个答案:

答案 0 :(得分:3)

我正在了解QWebEngine。这很酷。我有以下工作。

lambada捕获需要是&#34; =&#34;,或者#34;这个&#34;在发出信号的情况下。你还需要&#34; mutable&#34;修改捕获的副本。 toHtml()是异步的,因此即使您捕获html,在toHtml()中调用SomeFunction后也不太可能直接使用它。您可以通过使用信号和插槽来克服这个问题。

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;
}

答案 1 :(得分:0)

我认为问题更多是连接问题。您的代码在我的appli上工作正常:

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

...

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

...加载时间...

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