将Matplotlib嵌入到PyQt中作为自定义小部件

时间:2014-01-21 06:11:00

标签: qt python-2.7 matplotlib pyqt4

我正在尝试将python中的matplotlib嵌入到Qt Designer中作为自定义小部件,我在线跟踪其中一条指令,我将小部件提升为mplwidget.py并将代码编码为以下代码

from PyQt4 import QtGui
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
class MplCanvas(FigureCanvas):
    def __init__(self):
        self.fig = Figure()
        self.ax = self.fig.add_subplot(111)
        FigureCanvas.__init__(self, self.fig)
        FigureCanvas.setSizePolicy(self,
                               QtGui.QSizePolicy.Expanding,
                               QtGui.QSizePolicy.Expanding)

        FigureCanvas.updateGeometry(self)

class MplWidget(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.canvas = MplCanvas()
        self.vbl = QtGui.QVBoxLayout()
        self.vbl.addWidget(self.canvas)
        self.setLayout(self.vbl)

我给了我错误

Traceback (most recent call last):
File "C:\Users\l.cen\Documents\Guiexmaple\main.py", line 8, in <module>
from window import Ui_MainWindow
File "C:\Users\l.cen\Documents\Guiexmaple\window.py", line 106, in <module>
from mplwidget import MplWidget
 File "C:\Users\l.cen\Documents\Guiexmaple\mplwidget.py", line 9, in <module>
class MplCanvas(FigureCanvas):
File "C:\Users\l.cen\Documents\Guiexmaple\mplwidget.py", line 22, in MplCanvas
FigureCanvas.updateGeometry(self)
NameError: name 'self' is not defined

所以我删除了setSizePolicy和updateGeometry部分

然后它会给出

Traceback (most recent call last):
File "C:\Users\l.cen\Documents\Guiexmaple\main.py", line 83, in <module>
window= Main()
File "C:\Users\l.cen\Documents\Guiexmaple\main.py", line 74, in __init__
self.ui.setupUi(self)
File "C:\Users\l.cen\Documents\Guiexmaple\window.py", line 34, in setupUi
self.widget = MplWidget(self.centralwidget)
TypeError: __init__() takes exactly 1 argument (2 given)

我不确定自从我遵循指令中的所有步骤后发生了什么,任何与此相关的建议都会很棒。

如果有帮助,这是我的主体代码:

import sys
from PyQt4 import QtGui, QtCore
from window import Ui_MainWindow
import sqlite3
import os
import matplotlib.pyplot as plt
from datetime import datetime
import calendar
import numpy

os.chdir("C:\Data")
conn = sqlite3.connect('FBG.db')
c=conn.cursor()



class Main(QtGui.QMainWindow):


    def searching_database(self):
        self.ui.listWidget.clear()
        data = self.ui.Inputname.text()
        for df in c.execute("select name from sqlite_master where type='table'; "):
           strdf=str(df)
           if len(data)==0:
                break
           if strdf[3:(len(data)+3)] == data: # the name for df start from position 3 due to "[u "
            self.ui.listWidget.addItem(strdf[3:-3])
        else:
            pass

    def delete_selection(self):
        self.ui.listWidget_3.takeItem(self.ui.listWidget_3.currentRow())


    def clear_graph(self):
        self.ui.listWidget_3.clear()

    def adding_items(self):
        global b
        b=self.ui.listWidget.currentItem().text()
        b=str(b)

    def plot_graph(self):
        self.ui.listWidget_3.addItem(b)

        time1= QtCore.QDateTime(self.ui.dateTimeEdit.dateTime())
        date1 = time1.toPyDateTime()
        timestamp1 = calendar.timegm(date1.utctimetuple()) #return a integer value

        time2= QtCore.QDateTime(self.ui.dateTimeEdit_2.dateTime())
        date2 = time2.toPyDateTime()
        timestamp2 = calendar.timegm(date2.utctimetuple()) 

        time=[]
        data=[]
    for df in c.execute('''select * from '''+ b ):
        time= numpy.append(time, df[0])
        data= numpy.append(data, df[1])
        plt.scatter(time,data,label= b)
        plt.title("Time versus strain or temperture")
        plt.xlabel("Time")
        plt.ylabel("Strain or temperature")
        plt.legend()
        plt.show()
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.Inputname.textChanged.connect(self.searching_database)
        self.ui.listWidget.itemClicked.connect(self.adding_items)
        self.ui.pushButton.clicked.connect(self.plot_graph)
        self.ui.Delete.clicked.connect(self.delete_selection)
        self.ui.Clear.clicked.connect(self.clear_graph)

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    window= Main()
    window.show()
    app.exec_()

1 个答案:

答案 0 :(得分:2)

以下是一段可能对您有帮助的代码

#!/usr/bin/python
import sys
from PyQt4.QtGui import QWidget, QPushButton, QMainWindow, QMdiArea, QVBoxLayout, QApplication
from PyQt4.QtCore import Qt

from pylab import *
from matplotlib.backends.backend_qt4agg import (
    FigureCanvasQTAgg as FigureCanvas,
    NavigationToolbar2QTAgg as NavigationToolbar)



class MyMainWindow(QMainWindow):

    def __init__(self, parent=None):
        """
        """

        super(MyMainWindow,self).__init__(parent)
        self.setWidgets()

    def setWidgets(self, ):


        vBox = QVBoxLayout()
        mainFrame = QWidget()

        self._plotGraphButton = QPushButton("Plot Random Graph")
        self._plotGraphButton.clicked.connect(self.plotRandom)

        self._fig = figure(facecolor="white")
        self._ax = self._fig.add_subplot(111)

        self._canvas = FigureCanvas(self._fig)
        self._canvas.setParent(mainFrame)
        self._canvas.setFocusPolicy(Qt.StrongFocus)


        vBox.addWidget(self._plotGraphButton)
        vBox.addWidget(self._canvas)
        vBox.addWidget(NavigationToolbar(self._canvas,mainFrame))
        mainFrame.setLayout(vBox)
        self.setCentralWidget(mainFrame)

    def plotRandom(self, ):
        """
        """

        x = linspace(0,4*pi,1000)

        self._ax.plot(x,sin(2*pi*rand()*2*x),lw=2)
        self._canvas.draw()


if __name__ == '__main__':
    qApp = QApplication(sys.argv)
    MainWindow = MyMainWindow()

    MainWindow.show()
    sys.exit(qApp.exec_())

干杯