1

I have been searching for any info about injecting CSS into QML WebView. Doc says QML WebView is a light version of Qt Widgets WebView. So I assume it is not possible to inject CSS into WebView. Is not it?

1 Answer 1

3

A possible solution is to inject css through javascript (as I pointed out in this solution):

import QtQuick 2.14
import QtQuick.Window 2.14
import QtWebView 1.14

Window {
    visible: true
    width: 640
    height: 480
    QtObject{
        id: internals
        property string css: "div { background-color: salmon;}"
    }
    WebView{
        anchors.fill: parent
        url: "https://stackoverflow.com"
        onLoadingChanged: {
            if(loadRequest.status == WebView.LoadSucceededStatus){
                runJavaScript(loadCSS("foo", internals.css))
            }
        }
    }
    function loadCSS(name, css){
        var script = "
    (function() {
    css = document.createElement('style');
    css.type = 'text/css';
    css.id = '" + name + "'; " +
    "document.head.appendChild(css);
    css.innerText ='"  + css +"'" +
    "})()";
        return script;
    }
}

enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

thank you for your answer. runJavaScript() is it native or external method?
@Mikhail I do not understand you, explain yourself well, if you check the WebView docs you will see that it has that method: doc.qt.io/qt-5/qml-qtwebview-webview.html#runJavaScript-method

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.