2

How to apply custom font (font is in qrc) to some part of html content in WebEngineView?

2
  • Since that is *View you cannot edit content, only viewing. Or, as a workaround you can get page html code, change it and set it by calling WebEngineView.loadHtml()
    – folibis
    Jan 30, 2017 at 8:33
  • HTML content loaded with WebEngineView.loadHtml(). I can use custom font from QML like this: TextArea { font.family: "myFont" }. And it's working. The problem is how to use this font from HTML content using CSS in WebEngineView?
    – mroot
    Jan 30, 2017 at 9:32

1 Answer 1

1

I figured out how to use my custom font (but I'm not sure how safe is this):

  1. Add custom font to qrc: ://res/font/myfont.ttf;
  2. Create style.css in qrc with this content:

    @font-face {
      font-family: myfont;
      src: url('qrc:/res/font/myfont.ttf');
      font-weight: bold;
    }
    
    body {
        font-family: 'myfont';
        text-align: justify;
        line-height: 25px;
    }
    
  3. In QML when content loaded to WebEngineView add your style.css to HTML:

    WebEngineView {
        id: webEngineView
        onLoadingChanged: {
            if (loadRequest.status == WebEngineView.LoadSucceededStatus) {
            webEngineView.runJavaScript(
                "var headHTML = document.documentElement.getElementsByTagName('head')[0].innerHTML;" +
                "headHTML += '<link rel=\"stylesheet\" href=\"qrc:/css/styles.css\">';" + 
                "document.documentElement.getElementsByTagName('head')[0].innerHTML = headHTML;"
                );
            }                
        }
    }
    
  4. And last, run your app with this command line argument --disable-web-security

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.