The wiki is in the process of moving to Please make your edits there.

PySideTutorials_Clickable_button | Qt Wiki | Qt Project

English 日本語

A simple clickable button tutorial

In this tutorial, we’ll show you how to start handling with PySide’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 Hello World in the python console each time you press it.

Let’s starting by importing the necessary Qt classes and python sys class:

  1. import sys
  2. from PySide.QtCore import *
  3. from PySide.QtGui import *

Let’s also create a python function which writes “Hello World” to the console:

  1. # Greetings
  2. def sayHello():
  3.     print "Hello World!"

Now, as mentioned in Your first PySide application, you must create the QApplication which will run your PySide 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 sayHello() 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 sayHello() function:

  1. # Connect the button to the function
  2. button.clicked.connect(sayHello)

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

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

Full Code

  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  4. import sys
  5. from PySide.QtCore import *
  6. from PySide.QtGui import *
  8. def sayHello():
  9.     print "Hello World!"
  11. # Create the Qt Application
  12. app = QApplication(sys.argv)
  13. # Create a button, connect it and show it
  14. button = QPushButton("Click me")
  15. button.clicked.connect(sayHello)
  17. # Run the main Qt loop
  18. app.exec_()    

Now that you know the basics, can you get it to print your name?