gpt4 book ai didi

python - 为 PyQt5 网络引擎使用 html 中的本地文件

转载 作者:太空宇宙 更新时间:2023-11-04 00:28:23 26 4
gpt4 key购买 nike

我正在尝试将绘图嵌入到 PyQt5 网络引擎 View 中。我能够使用以下方法做到这一点:

open plotly in qwebview in interactive mode

如果您阅读它,文章会解释说您不能在使用网络引擎 View 时直接在 HTML 中包含 javascript(它在加载超过 2 MB 的文件时会出现问题)。但是,我试图做到这一点,以便 javascript 的源代码是 plotly-min.js 的本地副本(保存在项目文件夹中),这样使用该程序的任何人都不需要互联网连接来查看图表它产生。我尝试在 html 上遵循一些示例,但无济于事。

与互联网连接一起工作的原始代码是:

raw_html = '<html><head><meta charset="utf-8" />'
raw_html += '<script src="https://cdn.plot.ly/plotly-latest.min.js"></script></head>'
raw_html += '<body>'
raw_html += plot(fig, include_plotlyjs=False, output_type='div')
raw_html += '</body></html>'

temp_view = QWebEngineView()
temp_view.setHtml(graph)

如果我理解正确,我需要更改这部分:

<script src="https://cdn.plot.ly/plotly-latest.min.js">

我已经试过了:

<script type="text/javascript" src="file:///C:/Users/UserName/PycharmProjects/ProjectFolder/plotly-latest.min.js"></script>

老实说,我不懂 HTML。这是代码中唯一的 HTML(其余部分在 Python 3 中)。有谁知道为什么以上可能不起作用以及我需要更改什么?我怀疑我可能会以某种方式遇到上述问题所引用的 2 MB 限制,因为我在网上找到的关于如何在 HTML 中引用本地文件的不同变体似乎没有任何改变。

最佳答案

出于安全原因,许多浏览器禁止加载本地文件,但正如以下 forum 中所述您可以通过以下方式启用该功能:

sys.argv.append("--disable-web-security")

假设 .js 在您的 .py 文件旁边:

.
├── main.py
└── plotly-latest.min.js

你可以使用下面的例子:

import sys
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtCore import QDir, QUrl

import plotly
import plotly.graph_objs as go

sys.argv.append("--disable-web-security")
app = QApplication(sys.argv)

x1 = [10, 3, 4, 5, 20, 4, 3]
trace1 = go.Box(x = x1)
layout = go.Layout(showlegend = True)
data = [trace1]

fig = go.Figure(data=data, layout = layout)

path = QDir.current().filePath('plotly-latest.min.js')
local = QUrl.fromLocalFile(path).toString()

raw_html = '<html><head><meta charset="utf-8" />'
raw_html += '<script src="{}"></script></head>'.format(local)
raw_html += '<body>'
raw_html += plotly.offline.plot(fig, include_plotlyjs=False, output_type='div')
raw_html += '</body></html>'

view = QWebEngineView()
view.setHtml(raw_html)
view.show()

sys.exit(app.exec_())

enter image description here

关于python - 为 PyQt5 网络引擎使用 html 中的本地文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46653337/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com