Search code examples
javascripthtmlqtqtwebengine

Qt function runJavaScript() does not execute JavaScript code


I am trying to implement the displaying of a web page in Qt. I chose to use the Qt WebEngine to achieve my task. Here's what I did :

  • Wrote a sample web page consisting of a empty form.
  • Wrote a JS file with just an API to create a radio button inside the form.

In my code, it looks like this :

View = new QWebEngineView(this);
// read the js file using qfile
file.open("path to jsFile");
myJsApi = file.Readall();
View->page()->runjavascript (myjsapi);
View->page()->runjavascript ("createRadioButton(\"button1\");");

I find that the runJavaScript() function has no effect on the web page. I can see the web page in the output window, but the radio button I expected is not present. What am I doing wrong?


Solution

  • I think you will have to connect the signal loadFinished(bool) of your page() to a slot, then execute runJavaScript() in this slot.

    void yourClass::mainFunction()
    {
        View = new QWebEngineView(this);
    
        connect( View->page(), SIGNAL(loadFinished(bool)), this, SLOT(slotForRunJS(bool)));
    }
    
    void yourClass::slotForRunJS(bool ok)
    {
        // read the js file using qfile
        file.open("path to jsFile");
        myJsApi = file.Readall();
        View->page()->runJavaScript(myjsapi);
        View->page()->runJavaScript("createRadioButton(\"button1\");");
    }