Button Functions with PyQT




In this Tutorial, we're going to discuss how to create your own functions or methods for your buttons to execute when clicked in PyQT GUI applications.

Since exiting an application is a pretty universal need, and simple to code, we're going to just create our own exiting method.


    def close_application(self):
        print("whooaaaa so custom!!!")
        sys.exit()
This is a method within our Window Class. For now, we'll just print a custom message, and then run a sys.exit() to close everything.

Now, since the close_application method is a part of our Window class, to call it, all we need to do is self.close_application! So, now, we just modify the home method.


    def home(self):
        btn = QtGui.QPushButton("Quit", self)
        btn.clicked.connect(self.close_application)
        btn.resize(btn.minimumSizeHint())
        btn.move(0,0)
        self.show()
Here, we use .connect(self.close_application) to run our custom method instead.

Also, note the new btn.resize parameter.

Now, the full code looks like:

import sys
from PyQt4 import QtGui, QtCore

class Window(QtGui.QMainWindow):

    def __init__(self):
        super(Window, self).__init__()
        self.setGeometry(50, 50, 500, 300)
        self.setWindowTitle("PyQT tuts!")
        self.setWindowIcon(QtGui.QIcon('pythonlogo.png'))
        self.home()

    def home(self):
        btn = QtGui.QPushButton("Quit", self)
        btn.clicked.connect(self.close_application)
        btn.resize(btn.minimumSizeHint())
        btn.move(0,0)
        self.show()

    def close_application(self):
        print("whooaaaa so custom!!!")
        sys.exit()
    
def run():
    app = QtGui.QApplication(sys.argv)
    GUI = Window()
    sys.exit(app.exec_())


run()

There is also the new line of:

btn.resize(btn.minimumSizeHint())

There is sizeHint and minimumSizeHint, they both so similar things. The sizeHint code will return what QT thinks is the best side for your button. The minimumSizeHint will just return what QT thinks is the smallest reasonable size for your button.

Next up in this tutorial series, we're going to be talking about how to add a menubar to our application.


There exists 3 quiz/question(s) for this tutorial. for access to these, video downloads, and no ads.

The next tutorial:





  • PyQT Basic Tutorial
  • PyQT Application Structure
  • PyQT buttons
  • Button Functions with PyQT
  • PyQT Menubar
  • PyQT Toolbar
  • Pop up Message PyQT
  • PyQT Check box
  • PyQT Progress bar example
  • PyQT Dropdown button and QT Styles
  • PyQT Font widget
  • PyQT Color picker widget
  • PyQT Text Editor
  • PyQT open files to edit
  • PyQT file saving