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

标签 python pyqt pyqt5 plotly qwebengineview

我正在尝试将绘图嵌入到 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/

相关文章:

python - 如何创建一个包含元素 0 n 次的列表? Python

python - 在 Python 中将行从一个 CSV 附加到另一个

python - 按第二列排序的列中每组的 cumsum 追加到原始数据框

python - 用 Python3 合并两个视频

python - PyQt4 本地目录 View ,带有选择文件夹的选项

python - 如何在python中插入/编辑QAbstractListModel并自动更新qml?

python - pyqt中的一串连续的复选框

python-3.x - 在 pyqtgraph.ImageView() 上绘制线条

python - Pandas to_sql 更改数据库表中的数据类型

python - QSqlRelationalDelegate 显示foreign_key - 相关记录的id,而不是组合框中的名称/值