1

I was trying embed matplotlib in python into Qt Designer as a custom widget, i followed one of those instruction online, i promote the widget to mplwidget.py and i coded file as code following

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)

I gives me the error

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

so i delete the setSizePolicy and updateGeometry part

then it will give

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)

I'm not sure what happened exactly since i followed all the steps in the instruction, anything suggestions that could relate to this would be great.

if it helps, this is code for my main body:

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_()
9
  • Please fix your indentation and include the full traceback of the error. Commented Jan 21, 2014 at 19:53
  • Hi, indentation and full traceback of the error has been included. Commented Jan 21, 2014 at 22:33
  • are you sure you are running the version of the code you think you are running? I can not make sense of the NameError because you use self a few lines above. Commented Jan 21, 2014 at 22:37
  • It also looks like you are getting the error on import which makes me think that in your source that line is not indented properly. Commented Jan 21, 2014 at 22:38
  • I think the indentation should be alright, or otherwise it will give the error of indetation? I will check it again just in case. Sorry, i didn't understand when you say "running the version of the code you think you are running" ? What does that mean? Commented Jan 21, 2014 at 22:54

1 Answer 1

2

Here is a piece of code that might help you

#!/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_())

Cheers

Sign up to request clarification or add additional context in comments.

1 Comment

I use Pyside, and this answer really helped me. Creating a layout and adding the widget was exactly what I needed. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.