问题描述
我正在使用plotly和pyqt5(GUI开发),当我尝试下载/导出生成的图像时,会出现以下消息:
js: Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
我正在使用QtWebengine,下一个示例:
import plotly.offline as po
import plotly.graph_objs as go
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5 import QtCore,QtWidgets
import sys
def show_qt(fig):
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 += po.plot(fig,include_plotlyjs=False,output_type='div')
raw_html += '</body></html>'
fig_view = QWebEngineView()
# setHtml has a 2MB size limit,need to switch to setUrl on tmp file
# for large figures.
fig_view.setHtml(raw_html)
fig_view.show()
fig_view.raise_()
return fig_view
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
fig = go.figure(data=[{'type': 'scattergl','y': [2,1,3,1]}])
fig_view = show_qt(fig)
sys.exit(app.exec_())
解决方法
这是一条警告,警告您下载图像(将其转换为字节)的方式可能会导致安全错误,但是在这种情况下,您可以忽略它。如果要下载文件,则必须使用QWebEnginePage的downloadRequested信号:
$checkbox_value = $request->checkbox_value ? 1 : 0