user1976336
user1976336

Reputation: 217

Using functions from a different class to connect signals

Hello I am making a program and I am using a stackedLayout to show different "areas" within the program. I want to use classes to "separate" functions related to certain areas. For instance Area1 has a start button and a clear button and When the start button is pressed it runs the program, when the clear button is pressed the area is cleared. When I define the functions to start and clear within my main class the buttons work fine, but when I call them from another class nothing happens.

main.py

class Program(QtGui.QMainWindow, Interface.Ui_MainWindow):
    def __init__(self, parent=None):
        super(Program, self).__init__(parent)
        self.setupUi(self)

        run = hello()
        self.startButton.clicked.connect(run.hello1)
        self.clearButton.clicked.connect(run.hello2)

class hello(object):
    def hello1(self):
        print "start button"

    def hello2(self):
        print "stop button"

May someone please explain why nothing is being printed when I click on the buttons?

Upvotes: 1

Views: 819

Answers (1)

Avaris
Avaris

Reputation: 36745

You are not keeping a reference to your hello instance. So it's garbage collected after __init__ ends and is not available when you press your buttons.

Try storing it as a instance attribute (self.run), rather than local variable (run):

class Program(QtGui.QMainWindow, Interface.Ui_MainWindow):
    def __init__(self, parent=None):
        super(Program, self).__init__(parent)
        self.setupUi(self)

        self.run = hello()
        self.startButton.clicked.connect(self.run.hello1)
        self.clearButton.clicked.connect(self.run.hello2)

class hello(object):
    def hello1(self):
        print "start button"

    def hello2(self):
        print "stop button"

Upvotes: 2

Related Questions