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()
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()
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.