python - 如何在pyqt5中嵌入绘图图?
问题描述
我用谷歌搜索并找到了两个代码,我得到了相同的错误。有什么可以帮忙的吗?
from PyQt5.QtWebEngineWidgets import QWebEngineView
ImportError: QtWebEngineWidgets must be imported before a QCoreApplication instance is created
第一个代码: https ://github.com/plotly/plotly.py/issues/716
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_())
第二个代码:
from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets
import plotly.express as px
class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.button = QtWidgets.QPushButton('Plot', self)
self.browser = QtWebEngineWidgets.QWebEngineView(self)
vlayout = QtWidgets.QVBoxLayout(self)
vlayout.addWidget(self.button, alignment=QtCore.Qt.AlignHCenter)
vlayout.addWidget(self.browser)
self.button.clicked.connect(self.show_graph)
self.resize(1000,800)
def show_graph(self):
df = px.data.tips()
fig = px.box(df, x="day", y="total_bill", color="smoker")
fig.update_traces(quartilemethod="exclusive") # or "inclusive", or "linear" by default
self.browser.setHtml(fig.to_html(include_plotlyjs='cdn'))
if __name__ == "__main__":
app = QtWidgets.QApplication([])
widget = Widget()
widget.show()
app.exec()
解决方案
推荐阅读
- python - Python-sqlite3中2个表的数据合并问题
- c# - 如何修改此 BFS 算法?
- php - 防止 wordpress 标题中的换行和样式文本
- php - 不会从 elementor 表单中提取表单输入
- javascript - 使用 djs v13 播放本地音乐文件
- image - 在flatList中通过模态打开动态图像反应本机
- vue.js - Sass @use 不会在 Vue 组件中导入
- java - 是否可以将 QueryCursor 存储在 Firestore 上?
- python - 使用 subprocess.call() 调用 C 程序时的奇怪行为
- javascript - 如何在反应三纤维 MapControls 中限制平移距离