将MatPlotLib图插入QWidget类型

时间:2019-03-03 18:08:35

标签: python matplotlib pyqt pyqt5

我试图将MatPlotLib图插入QWidget类型的窗口小部件中,以便绘制来自传感器库的实时数据的图。想法是异步提取数据,将其转储到numpy中,然后使用MatPlotLib对其进行图形化处理。

我的问题是MatPlotLib不想用图形表示我建立的表单。我尝试将小部件分离到自己的类中,但是那也不起作用。所有在线教程似乎都以空白表格开头,然后从代码中构建,而不是引用现成的.ui文件。

下面的代码被简化以简化操作:

from PyQt5 import uic, QtCore
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QAction

import matplotlib.pylab as plt
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar

import numpy as np


class MyWindow(QMainWindow):

    def __init__(self):
        super(MyWindow, self).__init__()
        # importing ui that is made in Qt Designer
        uic.loadUi('MainForm.ui', self)

        # linking Exit option from File menu to exit action
        exitButton = QAction('Exit', self)
        exitButton.setShortcut('Ctrl+Q')
        exitButton.setStatusTip('Exit the program.')
        self.actionExit.triggered.connect(QApplication.quit)

        # add data
        data = np.array([0.7, 0.7, 0.7, 0.8, 0.9, 0.9, 1.5, 1.5, 1.5, 1.5])
        fig, ax1 = plt.subplots()
        bins = np.arange(0.6, 1.62, 0.02)
        n1, bins1, patches1 = ax1.hist(data, bins, alpha=0.6, density=False, cumulative=False)
        # plot
        self.plotWidget = FigureCanvas(plt.subplot)
        lay = QVBoxLayout(self.plotWidget)
        lay.setContentsMargins(0, 0, 0, 0)
        lay.addWidget(self.plotWidget)
        # add toolbar
        self.addToolBar(QtCore.Qt.BottomToolBarArea, NavigationToolbar(self.plotWidget, self))


if __name__ == "__main__":
    import sys

    app = QApplication(sys.argv)
    window = MyWindow()
    window.show()
    sys.exit(app.exec())

MainForm.ui代码为:

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>800</width>
    <height>736</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <widget class="QWidget" name="centralWidget">
   <widget class="QWidget" name="plotWidgetHolder" native="true">
    <property name="geometry">
     <rect>
      <x>11</x>
      <y>11</y>
      <width>771</width>
      <height>484</height>
     </rect>
    </property>
    <property name="styleSheet">
     <string notr="true">background-color: rgb(255, 255, 255);</string>
    </property>
   </widget>
   <widget class="QPushButton" name="pushButton">
    <property name="geometry">
     <rect>
      <x>320</x>
      <y>570</y>
      <width>93</width>
      <height>28</height>
     </rect>
    </property>
    <property name="text">
     <string>PushButton</string>
    </property>
   </widget>
  </widget>
  <widget class="QMenuBar" name="menubar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>800</width>
     <height>26</height>
    </rect>
   </property>
   <widget class="QMenu" name="menuFile">
    <property name="title">
     <string>File</string>
    </property>
    <addaction name="actionNew"/>
    <addaction name="actionOpen"/>
    <addaction name="separator"/>
    <addaction name="actionExit"/>
   </widget>
   <widget class="QMenu" name="menuData">
    <property name="title">
     <string>Data</string>
    </property>
    <addaction name="actionOpen_Data_Folder"/>
    <addaction name="actionOpen_in_Excel"/>
   </widget>
   <addaction name="menuFile"/>
   <addaction name="menuData"/>
  </widget>
  <widget class="QStatusBar" name="statusbar"/>
  <action name="actionNew">
   <property name="text">
    <string>New</string>
   </property>
  </action>
  <action name="actionOpen">
   <property name="text">
    <string>Open</string>
   </property>
  </action>
  <action name="actionOpen_in_Excel">
   <property name="text">
    <string>Open in Excel</string>
   </property>
  </action>
  <action name="actionOpen_Data_Folder">
   <property name="text">
    <string>Open Data Folder</string>
   </property>
  </action>
  <action name="actionExit">
   <property name="text">
    <string>Exit</string>
   </property>
  </action>
 </widget>
 <resources/>
 <connections/>
</ui>

使用此代码,我通常会得到一个错误代码“ AttributeError:'function'对象没有属性'set_canvas'”,并且该图会在其自己的MatPlotLib生成的窗口中弹出,而不是在较大的窗体中弹出。

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

您需要更换

self.plotWidget = FigureCanvas(plt.subplot)
lay = QVBoxLayout(self.plotWidget)
lay.setContentsMargins(0, 0, 0, 0)
lay.addWidget(self.plotWidget)

使用

self.plotWidget = FigureCanvas(fig)
self.setCentralWidget(self.plotWidget)

FigureCanvasQTAgg中的constructor需要一个图形,而一个QMainWidget已经具有一个布局。

正如ImportanceOfBeingErnest所说,您还应该使用fig = matplotlib.figure.Figure()来构建图形。 (然后您可以使用ax1 = fig.gca()获取轴)

修改: 要添加更多小部件,必须将图形添加到需要父小部件的布局中:

self.plotWidget = FigureCanvas(fig)
self.someButton = QPushButton('click me')
container = QWidget()
layout = QGridLayout()
layout.addWidget(self.plotWidget,0,0)
layout.addWidget(self.someButton,1,0)
container.setLayout(layout)
self.setCentralWidget(container)