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?

Bob
  • 1,433
  • 1
  • 16
  • 36

1 Answers1

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

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • thank you for your answer. `runJavaScript()` is it native or external method? – Bob Mar 19 '20 at 16:49
  • @Mikhail I do not understand you, explain yourself well, if you check the WebView docs you will see that it has that method: https://doc.qt.io/qt-5/qml-qtwebview-webview.html#runJavaScript-method – eyllanesc Mar 19 '20 at 16:50