QPushButton.clicked.connect doesn't seem to work

Viewed 29

I am trying to decouple entirely my GUI from my controller class, and for some reason I can't seem to manage to connect my buttons from outside of my GUI class itself.

Here's a small example of what I mean :

import sys
from PySide6 import QtWidgets


class Gui(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Gui, self).__init__(parent)
        layout = QtWidgets.QHBoxLayout(self)
        self.button = QtWidgets.QPushButton("Do stuff")
        layout.addWidget(self.button)


class Controller(object):
    def do_stuff(self):
        print("something")


def startup(parent):
    ctrl = Controller()
    gui = Gui(parent)
    gui.button.clicked.connect(ctrl.do_stuff)
    return gui


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    dialog = QtWidgets.QDialog()
    gui = startup(dialog)
    dialog.show()
    sys.exit(app.exec_())

I would expect this code, when run, to display a GUI with one push button (which it does), and when pressing the push button, I'd expect the word "something" to get printed. However this doesn't seem to be the case. I might just be too tired, but I can't find the solution.

What am I missing?

Thanks a lot in advance!

1 Answers
ctrl = None
gui = None
def startup(parent):
    global ctrl
    global gui
    ctrl = Controller()
    gui = Gui(parent)
    gui.button.clicked.connect(ctrl.do_stuff)
    return gui

try this, and it does work. when the variable is in the function, it will be destroyed before the function is finished. the global variable is not a good coding style but is a simple way to figure out your confusion.

Related