WebView组件忽略自定义字体

问题描述 投票:1回答:1

PyQt5有一个名为WebView的组件(不是QWebView!),它可以用loadHtml方法加载html。如果传递给方法的字符串包含对外部字体的引用,则忽略该字体。

在qml文件中加载html:

mainWebView.loadHtml(article); // mainWebView is the id of a WebView component

在py文件中准备html字符串:

with open(CSS_PATH, 'r') as f:
    css_style = f.read()

article = "<html><head><style>%s</style><title>%s</title></head><body>%s</body></html>" % (css_style, article['title'], article['body'])

在css文件中获取和设置外部字体:

@font-face {
  font-family: "AvenirNext";
  src: url("AvenirNext-Regular.ttf") format("truetype");
}

html *
{
   color: #e6e6e6;
   font-family: "AvenirNext";
   background-color: #494845;
   margin-left: 14px;
}

如果我在CSS中使用font-family: "Courier New"字体工作正常。只有当我从文件夹中获取某些字体时,才会被忽略。我将ttf文件放在app根文件夹和css文件所在的文件夹中,以防万一。链接到组件:https://doc.qt.io/qt-5.11/qml-qtwebview-webview.html

python css pyqt qml pyqt5
1个回答
1
投票

根据docs

loadHtml无效(字符串HTML,URL的baseUrl)

将指定的html内容加载到Web视图。

此方法提供url属性的低级替代,该属性通过URL引用HTML页面。

外部对象(如HTML文档中引用的样式表或图像)应相对于baseUrl定位。例如,如果从http://www.example.com/documents/overview.html(基本URL)检索html,则使用相对url,diagram.png引用的图像应位于http://www.example.com/documents/diagram.png

.css,.js或任何外部元素将相对于baseUrl,它是setHtml()的第二个参数。所以解决方案是将它传递给应该在本地文件夹中的虚构文件的URL。

卖弄.朋友

import os
import sys
from PyQt5 import QtCore, QtGui, QtQml

if __name__ == '__main__':
    app = QtGui.QGuiApplication(sys.argv)
    engine = QtQml.QQmlApplicationEngine()
    dir_path = os.path.dirname(os.path.abspath(__file__))
    CSS_PATH = "styles.css"
    with open(os.path.join(dir_path, CSS_PATH), 'r') as f:
        css_style = f.read()
        article = {"title": "title1", "body": "<H1> Body"}
        article = "<html><head><style>%s</style><title>%s</title></head><body>%s</body></html>" % (css_style, article['title'], article['body'])
        baseUrl = QtCore.QUrl.fromLocalFile(os.path.join(dir_path, 'index.html'))
        engine.rootContext().setContextProperty("article", article)
        engine.rootContext().setContextProperty("baseUrl", baseUrl)
    qml_filename = os.path.join(dir_path, 'main.qml')
    engine.load(QtCore.QUrl.fromLocalFile(qml_filename))
    if not engine.rootObjects():
        sys.exit(-1)
    sys.exit(app.exec_())

main.qml

import QtQuick 2.5
import QtQuick.Window 2.2
import QtWebView 1.1

Window {
    visible: true
    width: 640
    height: 480
    WebView{
        id: mainWebView
        anchors.fill: parent
    }
    Component.onCompleted: mainWebView.loadHtml(article, baseUrl)
}

我假设该项目具有以下结构:

|-- AvenirNext-Regular.ttf
|-- main.py
|-- main.qml
`-- styles.css
© www.soinside.com 2019 - 2024. All rights reserved.