3

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?

3 Answers 3

9

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\");");
}
Sign up to request clarification or add additional context in comments.

1 Comment

Glad to hear it! Feel free to accept the answer if it suited you, as it can help other people as well.
0

I had this problem, runJavascript didn't have any effect. I had to put some html content into the view (with page().setHtml("") before running it.

Comments

0

Check the application output, it might contain JavaScript errors. Even if your JS code is valid, you might encounter the situation where the script is run before DOMContentLoaded event, that is document.readyState == 'loading'. Therefore, the DOM might not be available yet, as well as variables or functions provided by other scripts. If you depend on them for your code to run, when you detect this readyState, either wait for the event or try calling the function later, after a timeout. The second approach with timeout might be needed if you need to get the result of the code execution, as this can be done only synchronously.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.