I googled and found two codes and I got same below error. any can help?
from PyQt5.QtWebEngineWidgets import QWebEngineView
ImportError: QtWebEngineWidgets must be imported before a QCoreApplication instance is created
1st code: 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_())
2nd code:
How to have plotly graph as PyQt5 widget?
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()