2017-10-09 116 views
0

我试图在PyQt5 web引擎视图中嵌入一个密谋图。我能这样做使用以下:在html中使用本地文件作为PyQt5 web引擎

open plotly in qwebview in interactive mode

如果你读它,文章解释说,使用webengine视图时,你不能直接包含在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中的本地文件似乎并没有改变任何东西。

回答

1

出于安全原因,许多浏览器禁用的本地文件的加载,但在下面的说明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

+0

谢谢你,完美的工作! –

相关问题