Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
585 views
in Technique[技术] by (71.8m points)

python - Google Fonts (ttf) being ignored in QtWebEngine when using @font face

I am trying to load a google font to my pyqt5 QtWebEngine app.

The app loads a local html file with css stying. I used font face to load the ttf file as below:

@font-face {
font-family: "Work Sans";
src: url("C:UsersGodwinTIATfontsWorkSans-Regular.ttf") format('truetype');
}

body {
font-family: "Work Sans";
background-color: #eef0f2;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you are using setHtml() then as indicated by the docs the external resources will be relative to the url that you pass as second parameters:

void QWebEngineView::setHtml(const QString &html, const QUrl &baseUrl = QUrl())

[...]

External objects, such as stylesheets or images referenced in the HTML document, are located relative to baseUrl.

[...]

So in your case the solution is:

import os
from PyQt5 import QtCore, QtGui, QtWidgets, QtWebEngineWidgets

if __name__ == "__main__":
    import sys
    sys.argv.append("--disable-web-security")
    app = QtWidgets.QApplication(sys.argv)
    wnd = QtWidgets.QWidget()
    genVLayout = QtWidgets.QVBoxLayout(wnd)
    verticalLayout_7 = QtWidgets.QVBoxLayout()
    webEngineViewGen = QtWebEngineWidgets.QWebEngineView(wnd)
    webEngineViewGen.setUrl(QtCore.QUrl("about:blank"))
    with open('main.html','r') as fh:
        html = fh.read()
        current_dir = os.path.dirname(os.path.abspath(__file__))
        url = QtCore.QUrl.fromLocalFile(os.path.join(current_dir, "main.html"))
        webEngineViewGen.setHtml(html, url)
    verticalLayout_7.addWidget(webEngineViewGen)
    genVLayout.addLayout(verticalLayout_7)
    wnd.show()
    sys.exit(app.exec_())

Or simply use the load() method:

import os
from PyQt5 import QtCore, QtGui, QtWidgets, QtWebEngineWidgets

if __name__ == "__main__":
    import sys
    sys.argv.append("--disable-web-security")
    app = QtWidgets.QApplication(sys.argv)
    wnd = QtWidgets.QWidget()
    genVLayout = QtWidgets.QVBoxLayout(wnd)
    verticalLayout_7 = QtWidgets.QVBoxLayout()
    webEngineViewGen = QtWebEngineWidgets.QWebEngineView(wnd)
    webEngineViewGen.setUrl(QtCore.QUrl("about:blank"))
    current_dir = os.path.dirname(os.path.abspath(__file__))
    url = QtCore.QUrl.fromLocalFile(os.path.join(current_dir, "main.html"))
    webEngineViewGen.load(url)
    verticalLayout_7.addWidget(webEngineViewGen)
    genVLayout.addLayout(verticalLayout_7)
    wnd.show()
    sys.exit(app.exec_())

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...