Nominate our 2022 Qt Champions!

Access to a QWebElement

  • Hello,

    i use a QWebEngineView in my Qt Project and I would like to know how to access to web elements of my HTML page ?

    is there any solution, such as QWebElement in QWebView ?


  • If you want to set your elements in your View you can use normal Javascript lke this.

    Code example took from my project (use Jquery)
    Notice the "null" in the evaluateJavascript call at the end, speed up the process
    Note: This is for QWebView but QWebEngineView should work just the same. I'm not using it yet until it's more stable.

    QString jsToExecute = QString("$('#name-workout').val( '%1' ); ").arg(name);
    jsToExecute += QString("$('#plan-workout').val( '%1' ); ").arg(planEscaped);
    jsToExecute += QString("$('#creator-workout').val( '%1' ); ").arg(creatorEscaped);
    jsToExecute += QString("$('#description-workout').val( '%1' ); ").arg(descriptionEscaped);
    jsToExecute += QString("$('#select-type-workout').val( %1 );").arg(type);
    jsToExecute += "$('#select-type-workout').selectpicker('refresh');";
    ui->webView_createWorkout->page()->mainFrame()->documentElement().evaluateJavaScript(jsToExecute + "; null");

  • @maximus


    Is there any parameter/function to call before to activate Javascript ?
    Or when call evaluateJavaScript/runJavaScript exactly ?

    I try for example to select the second item of a HTML combobox like this :

    // JQuery

    • QFile file;
    • QByteArray jQuery;
    • file.setFileName("/home/user/soft/jquery.js");
    • jQuery = file.readAll();
    • jQuery.append("\nvar qt = { 'jQuery': jQuery.noConflict(true) };");
    • file.close();

    // Request

    • QString name = "ARCHI2";
    • QString jsToExecute = QString("$('#elem_name').val( '%1' ); ").arg(name);
    • view->page()->runJavaScript(jsToExecute);

    but it does not work...

  • Good question, with QWebView you don't have to do anything as Javascript is enable by default, I think the same is true for QWebEngineView.

    If you have control over the html page, I suggest you try the "jsToExecute" code in the javascript part of the html first to see if it's working, then move the code to the Qt side with the variables.

    Not sure I understand the code above "//Request", you can load jquery in your html page (if you have control of it).
    Good luck!

  • @maximus

    It's in the Qt side which does not work.
    When I call a javascript function (contained in my HTML page), nothing works except the "alert()" javascript function...

    I can't modify the content of the webpage

  • have you tried a simple alert from your Qt to Js?

    QString jsCode = "alert('helloWorld');";
    ui->webView_studio->page()->mainFrame()->documentElement().evaluateJavaScript(jsCode + "; null");

    if this works then the problem is the syntax of your javascript inside Qt.

Log in to reply