[Python] Passing data between classes with Signals in PyQt

Discussão em 'Python' iniciado por Stack, Agosto 18, 2025.

  1. Stack

    Stack Membro Participativo

    I have got two different classes that I need to connect using a signal that sends text in a variable from one class, to another.

    The first class is a Matplotlib figure. I added a QPushButton in the navigation toolbar to access a QDialog (which is the other class) with a QLineEdit. I need to send the text written in the QLineEdit to the Matplotlib figure´s class, using a variable, so I can create a note in the figure.

    This is the code so far:

    class Dialog(QDialog):

    list_of_notes = [] #I create a list to add text, each time I open the QDialog

    def __init__(self):
    #A lot of stuff in here

    def printVariable(self, text):
    Dialog.lisf_of_notes.append(text)
    MatplotlibFigure().addNote()

    self.close()

    class MatplotlibFigure(QMainWindow):
    def __init__(self):
    #A lot of stuff in here

    self.axes = self.figure_canvas.figure.add_subplot(111)

    def addNote(self):
    for i,s in enumerate(Dialog.list_of_notes):
    note = self.axes.annotate(i, xy=(0.2, 0.2)) #This is the note I want to create
    note.draggable()
    self.figure_canvas.draw_idle()


    So, when I press the button "Accept" in the QDialog I can see that the text is added to the list, each time that I open the dialog. But, when I want to create the note from the last object that I added to the list, in the for loop nothing happens.

    What is the problem? Hope you can help me.

    ----------------Edit-----------------------------


    I´ve made some modifications. I created a signal mysignal to emit the variable text, which have the text that I wrote in the QDialog.

    This is the modificated code:

    class Dialog(QDialog):
    def __init__(self, my_figure):

    mysignal = pyqtSignal(str)

    self.my_figure = MatplotlibFigure()
    QDialog.__init__(self)

    self.connect(self.btn_accept, SIGNAL("clicked()"), self.send_text)
    self.mysignal.connect(self.printVariable)

    def send_text(self): #I get the text from the QLineEdit and send it using
    text = self.lineEdit.text() #the created signal
    self.mysignal.emit(text)

    def printVariable(self, text):
    self,my_figure.addNote(text)
    self.close()

    class MatplotlibFigure(QMainWindow):
    def __init__(self):
    QMainWindow.__init__(self)
    self.notes_list =[]

    def openDialog(self, text): #I open the QDialog clicking a button
    textMat = Dialog(text)
    textMat.exec_()

    def addNote(self, text):
    self.notes_list.append(text)

    notes = self.axes.annotate(text, xy=(0.2, 0.2), bbox = dict(facecolor="red"))
    notes.draggable()
    self.figure_canvas.draw_idle()


    So, I open the QDialog and I can write the text. It is added to the list correctly, but the note is still not drawn in the figure.

    Continue reading...

Compartilhe esta Página