-1

I would like to know why when I do btn.clicked.connect(self.close_application()) the program closed instantly. It seems like self.close_application executed even though I did not click the print button. However, it works as intended when I use btn.clicked.connect(self.close_application).

Can anyone explain to me why using self.close_applciation() results in my Q window to be instantly closed without even me clicking the "print" button?

class Window(QtGui.QMainWindow):

    def __init__(self):
        super(Window, self).__init__()
        self.setGeometry(50,50,500,500)
        self.setWindowTitle("Kenny")

        self.home()
        self.show()

    def home(self):
        self.FullName()
        self.show()

    def FullName(self):
        win = QWidget(self)

        flo=QFormLayout()
        btn = QtGui.QPushButton("&Print",self)
        btn.clicked.connect(self.close_application)
        flo.addRow(btn ,QPushButton("Cancel"))
        self.setCentralWidget(win)
        win.setLayout(flo)        
        win.show()

    def close_application(self):
        print("Bye Bye")
        sys.exit() 



def run():
    app = QtGui.QApplication(sys.argv)
    GUI = Window()
    sys.exit(app.exec_())


run()
Nisse Engström
  • 4,738
  • 23
  • 27
  • 42
meric
  • 23
  • 4

1 Answers1

0

Because when you write btn.clicked.connect(self.close_application()), self.close_application() is executed immediately (and the result of the function would be sent to btn.clicked.connect, but at that time the application is already closed).

When you write btn.clicked.connect(self.close_application) it is not - because you did not call it.

Instead, this code sends the reference to bound method self.close_application, to btn.clicked.connect, to be executed when the button is clicked.


To compare it with another example:

def f():
    print('ffff')

calling f() prints ffff, but just using reference to f does not print anything:

a = f()  # prints ffff
b = f    # does not print anything

b()      # prints ffff
zvone
  • 18,045
  • 3
  • 49
  • 77
  • Thanks for the help. So you are saying that using `self.close_application()` result in `self.close_application()` to be executed first which result in the window to exit whereas using `self.close_application` result in this function to be executed only when the the button is clicked? – meric Sep 07 '18 at 00:24
  • @meric Yes. [This](https://stackoverflow.com/q/706721/1994235) post on Stack Overflow might be of interest to you as it explains how you can pass a reference to a method, to another method (which is what you want to do). – three_pineapples Sep 07 '18 at 07:45