How to use matplotlib with PyQt4

☆樱花仙子☆ 提交于 2020-05-23 11:00:09

问题


I want to plot a figure with embedded matplotlib in PyQt. I am using Qt Designer for the main window, and writing python code for the signal and slots connexion part.

So my code looks like this :

import sys
from PyQt4 import QtCore, QtGui, uic
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas 
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np


qtCreatorFile = "main.ui" # my Qt Designer file 

Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile)

class MyApp(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        Ui_MainWindow.__init__(self)
        self.setupUi(self)

        self.figure = plt.figure()

        self.canvas = FigureCanvas(self.figure)

        self.csvbutton.clicked.connect(self.plot)

    def plot(self):

        filePath="/path to csv file here"
        df= pd.read_csv(str(filePath),index_col='date')
        df.index = pd.to_datetime(df.index, unit='s')
        ax = self.figure.add_subplot(111)
        ax.hold(False)
        ax.plot(df, '*-')
        self.canvas.draw()



if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    window = MyApp()
    window.show()
    sys.exit(app.exec_())

My main problem is the connexion between the Qt Designer file and the python code, I couldn't set a canvas widget directly in Qt Designer and I'm still struggling to find where the error lays in my code. Your help is very appreciated, thank you.


回答1:


In order to use matplotlib in Qt Designer can not be done directly, for this we must promote a QWidget to use FigureCanvas or better a class that inherits from it as I show below, first we create a class called Canvas in file called canvas.py:

canvas.py

from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas 
import matplotlib.pyplot as plt

class Canvas(FigureCanvas):
    def __init__(self, parent=None):
        self.figure = plt.figure()
        FigureCanvas.__init__(self, self.figure)
        self.setParent(parent)

After creating the design through Qt Designer, we have all the elements we want, but where we want to place the argument we use the Widget element that is in Containers, and we name it canvas:

Then we promote it by right click and choose the option promoted to ...:

Obtaining what is shown in the following image, in Promoted Class Name we place Canvas as the name of the class, and in Header File we place canvas.h (in Header File the file.py file is placed, for example package.subpackage.file.h), then press Add and after Promote:

At the end we get a file structure similar to the following:

.
├── canvas.py
└── main.ui

Then we create the file main.py where we place your code with small variations:

main.py

import matplotlib
matplotlib.use('Qt4Agg')

import sys
from PyQt4 import QtCore, QtGui, uic
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np


qtCreatorFile = "main.ui" # my Qt Designer file 

Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile)

class MyApp(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        Ui_MainWindow.__init__(self)
        self.setupUi(self)
        self.csvbutton.clicked.connect(self.plot)

    def plot(self):

        filePath="data.csv"
        df= pd.read_csv(str(filePath),index_col='date')
        ax = self.canvas.figure.add_subplot(111)
        ax.hold(False)
        ax.plot(df, '*-')
        self.canvas.draw()



if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    window = MyApp()
    window.show()
    sys.exit(app.exec_())

In the end we get the following:

You can find the complete project here


If you want to add the NavigationToolbar you can use the following code:

...
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar 

...

class MyApp(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        Ui_MainWindow.__init__(self)
        self.setupUi(self)
        self.addToolBar(NavigationToolbar(self.canvas, self))
        ...



来源:https://stackoverflow.com/questions/45369725/how-to-use-matplotlib-with-pyqt4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!