QWebEngineView Best Way to Wait for Asynchronous Data



  • What is the best way to receive data if asynchronous? When the user clicks a QPushButton, I would like to query for data, however the runjavascript call takes too long to retrieve the data.

    I have tried the following:

    void MainWindow::getInformation()  // slot
    {
        MyData data;
        m_webEngineView->executeCommand("getData(\'id_name\')");
        // problem is here because when the following call is made
        //  the data has not been updated yet
        data = m_webEngineView->getData();
    }
    

    Snippet from WebEngineView

    void MyWebEngineView::executeCommand(QString cmd)
    {
        page()->runJavaScript(cmd, myFunction);
    }
    void MyWebEngineView::myFunction(QVariant myvar)
    {
        setData(myvar);
    }
    void MyWebEngineView::setData(QVariant myvar)
    {
        // manipulate myvar to fill in m_data
        m_data = myvar.toMyData();
    }
    MyData MyWebEngine::getData()
    {
        return m_data;
    }
    

    Thanks in advance for any help.



  • Hi and welcome to devnet,

    the problem is that you want a synchronous method MainWindow::getInformation() using asynchronous API.

    My suggestion is to have a signal in your MyWebEngineView and emit it when the callback is executed

    // MyWebEngineView.h
    class MyWebEngineView:....
    {
    Q_SIGNALS:
        void dataReceived();
    };
    
    // MyWebEngineView.cpp
    void MyWebEngineView::setData(QVariant myvar)
    {
        m_data = myvar.toMyData();
        
        Q_EMIT dataReceived();
    }
    

    and then connect this signal to a slot in MainWindow

    connect(m_webEngineView, &MyWebEngineView::dataReceived, this, &MainWindow::handleData);
    
    void MainWindow::handleData()
    {
        Mydata data = m_webEngineView->getData();
    
        // Use data
    }
    


  • @mcosta Your wording of my question was better. Thanks for the reply! I guess I was being lazy and hoping to avoid having 2 functions to call one. :-D


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.