Bootstrap

pyqt与echart交互

由于echart的文件渲染的原因,图像载入需要一定的时间
第一步:定义绘图模板,保存为test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="echarts.min.js"></script>
    <style type="text/css">
        #container {
            height: 100%;
            width: 100%;
            position: absolute;
        }

        body {
            margin: 0;
            padding: 0;
            overflow: hidden
        }
    </style>
    <title>Echarts</title>
</head>
<body style="height: 100%; margin:0">
<!-- 用来设置option -->
<div id="container" style="height: 100%"></div>
</body>
<script type="text/javascript">

    var myChart = echarts.init(document.getElementById("container"))

    function setChartOption(jsonData) {
        console.log(jsonData)
        myChart.setOption(jsonData)
        window.onresize = myChart.resize();
        return JSON.stringify(jsonData)
    }

    function resize() {
        window.onresize = myChart.resize();
    }

</script>
</html>

第二步:在布局中添加QWebEngineView
需要额外安装pyqt的拓展包pip install PyQtWebEngine

from PyQt5.QtWebEngineWidgets import QWebEngineView
    def pic_echart(self):

        #清空图像,防止后续在布局中反复添加绘图
        if self.verticalLayout_11.count()>0:
            self.verticalLayout_11.removeItem(self.verticalLayout_11.itemAt(0))

        self.statusBar().showMessage("图像加载中...")
        #实例化类用于加载html
        radar_view = QWebEngineView()
        
        radar_view.load(QUrl("file:///"+"html/radar.html"))  

        self.verticalLayout_11.addWidget(radar_view)
        self.statusBar().showMessage("图像加载完毕")

第三步:编写js语句,动态控制图像加载
编写控制函数时,加载页面和控制页面要分开编写,不然无法运行runJavaScript函数

 #加载坐标轴
    def load_echarts(self):
        #清空布局,重新载入图片
        if self.verticalLayout_3.count() > 0:
            self.verticalLayout_3.removeItem(self.verticalLayout_3.itemAt(0))

        #echarts绘图
        self.weather = QWebEngineView()
        self.weather.load(QUrl("file:///" + "weather.html"))  # 注意格式,绝对路径 
        self.verticalLayout_3.addWidget(self.weather)
        self.statusBar().showMessage("图像加载完毕")

    def changeWeather(self):

        self.label_19.setText("{}未来十五天气温走势图".format(self.ComboBox_2.currentText()))
        if self.weather.page():
            jscode = "weather({},{},{})".format(self.date_forecast,self.high,self.low)
            self.weather.page().runJavaScript(jscode)

;