Qt for Python Tutorial ClickableButton

From Qt Wiki
Jump to: navigation, search

A simple clickable button tutorial

In this tutorial, we'll show you how to start handling with Qt for Python's signals and slots. Basically, this Qt feature allows your graphical widgets to communicate with other graphical widgets or your own python code. Our application will create a clickable button which will show Button clicked, Hello! in the python console each time you click it.

Let's starting by importing the necessary PySide2 classes and python sys module:

1 import sys
2 from PySide2.QtWidgets import QApplication, QPushButton

Let's also create a python function which writes the message to the console:

1 # Greetings
2 def say_hello():                                                                                     
3     print("Button clicked, Hello!")

Now, as mentioned in previous examples you must create the QApplication which will run your PySide2 code:

1 # Create the Qt Application
2 app = QApplication(sys.argv)

Let's create the clickable button, a QPushButton. We pass a python string on the constructor which will label the button:

1 # Create a button
2 button = QPushButton("Click me")

Before we show the button, we must connect it to the say_hello() function that we defined previously. For now, there are two ways of doing this - by using the old style or the new style. The new style is more pythonic and that's what we'll use here. You can find more information about both approaches in Signals_and_Slots_in_PySide. The QPushButton has a predefined signal called clicked which is triggered every time that the button is pressed. We'll just connect this signal to the say_hello() function:

# Connect the button to the function
button.clicked.connect(say_hello)

Finally, we show the button and start the Qt main loop:

1 # Show the button
2 button.show()
3 # Run the main Qt loop
4 app.exec_()

Full Code

 1 #!/usr/bin/python
 2 # -'''- coding: utf-8 -'''-
 3 
 4 import sys                                                                                          
 5 from PySide2.QtWidgets import QApplication, QPushButton                                                                                                                                                                                                                                                                  
 6                                                                                                     
 7 def say_hello():                                                                                     
 8  print("Button clicked, Hello!")                                                                    
 9                                                                                                     
10 # Create the Qt Application                                                                         
11 app = QApplication(sys.argv)                                                                        
12 # Create a button, connect it and show it                                                           
13 button = QPushButton("Click me")                                                                    
14 button.clicked.connect(say_hello)                                                                    
15 button.show()                                                                                       
16 # Run the main Qt loop                                                                              
17 app.exec_()

A button to exit the application

Following the same idea, we can create a a QPushButton that closes the application when clicked.

 1 from PySide2.QtWidgets import QApplication, QPushButton
 2 
 3 if __name__ == "__main__":
 4     # Create a QApplication
 5     app = QApplication([])
 6 
 7     # Create a button
 8     button = QPushButton('Exit')
 9 
10     # Connect the button "clicked" signal to the exit() method
11     # that finishes the QApplication
12     button.clicked.connect(app.exit)
13 
14     button.show()
15     app.exec_()

Another example

Take a look of the following code, it follows the same idea previously described but interacting with other python modules

 1 import sys
 2 import random
 3 from PySide2 import QtCore, QtWidgets, QtGui
 4 
 5 class MyWidget(QtWidgets.QWidget):
 6     def __init__(self):
 7         QtWidgets.QWidget.__init__(self)
 8 
 9         self.hello = ["Hallo Welt", "你好,世界", "Hei maailma",
10             "Hola Mundo", "Привет мир"]
11 
12         self.button = QtWidgets.QPushButton("Click me!")
13         self.text = QtWidgets.QLabel("Hello World")
14         self.text.setAlignment(QtCore.Qt.AlignCenter)
15 
16         self.layout = QtWidgets.QVBoxLayout()
17         self.layout.addWidget(self.text)
18         self.layout.addWidget(self.button)
19         self.setLayout(self.layout)
20 
21         self.button.clicked.connect(self.magic)
22 
23 
24     def magic(self):
25         self.text.setText(random.choice(self.hello))
26 
27 
28 if __name__ == "__main__":
29     app = QtWidgets.QApplication(sys.argv)
30 
31     widget = MyWidget()
32     widget.show()
33 
34     sys.exit(app.exec_())