2017-07-28 62 views
0

我想在QWebEngineView打開我用toHtml(網頁的HTML代碼)功能QWebEnginePage類這樣獲取HTML從QWebEnginePage在QWebEngineView採用的Lamda

QWebEnginePage *page = ui->widget->page(); 
QString HTML = ""; 
page->toHtml([&HTML](QString html){qDebug() << "code \n\n\n" << html;}); 

HTML頁面的HTML代碼出現在沒有問題 qDebug好這裏的問題是,當我想用​​HTML字符串的函數外,當我顯示HTML varible它等於零而空的大小 所以我想這個

QWebEnginePage *page = ui->widget->page(); 
QString HTML = ""; 
page->toHtml([&HTML](QString html){HTML = html;}); // crash 
qDebug() << "i want to use HTML here outside the function = " << HTML; 

但程序崩潰的演出所以我應該怎麼做,我把HTML數據的HTML變量,所以我可以提前使用它的功能外
感謝

回答

1

你的問題是由拉姆達是異步運行的事實造成的。所以它真的被稱爲在你退出了你調用toHtml方法的方法,並且也解釋了崩潰 - HTML是已經退出的方法中的一個局部變量,所以lambda只是隨機地破壞了以前被HTML佔用的內存變量。

你想在這裏做什麼是同步的東西,即阻止你的方法,直到lambda執行。它可以用QEventLoop來完成,但是這需要涉及從lambda發送特殊信號來指示lambda完成執行的事實。所以它看起來有點像這樣(未測試):

class MyClass: public QObject 
{ 
    Q_OBJECT 
public: 
    MyClass(QWebEnginePage & page, QObject * parent = 0); 

    void notifyHtmlReceived(); 

    QString getHtml(); 
    void setHtml(const QString & html) { m_html = html; } 

Q_SIGNALS: 
    void htmlReceived(); 

private Q_SLOTS: 
    void requestHtmlFromPage(); 

private: 
    QWebEnginePage & m_page; 
    QString m_html; 
}; 

MyClass::MyClass(QWebEnginePage & page, QObject * parent) : 
    QObject(parent), 
    m_page(page) 
{} 

void MyClass::notifyHtmlReceived() 
{ 
    emit htmlReceived(); 
} 

QString MyClass::getHtml() 
{ 
    QEventLoop loop; 
    QObject::connect(this, SIGNAL(htmlReceived()), &loop, SLOT(quit())); 

    // Schedule the slot to run in 0 seconds but not right now 
    QTimer::singleShot(0, this, SLOT(requestHtmlFromPage())); 

    // The event loop would block until the lambda receiving the HTML is executed 
    loop.exec(); 

    // If we got here, the html has been received and the result was saved in m_html 
    return m_html; 
} 

void MyClass::requestHtmlFromPage() 
{ 
    m_page.toHtml([this](QString html) 
        { 
         this->setHtml(html); 
         this->notifyHtmlReceived(); 
        }); 
}