Qt wiki will be updated on October 12th 2023 starting at 11:30 AM (EEST) and the maintenance will last around 2-3 hours. During the maintenance the site will be unavailable.

Qt for Python Tutorial ClickableButton: Difference between revisions

From Qt Wiki
Jump to navigation Jump to search
No edit summary
No edit summary
 
(9 intermediate revisions by 4 users not shown)
Line 1: Line 1:
[[Category:LanguageBindings::PySide]]
== A simple clickable button tutorial ==


'''English''' [[PySideTutorials_Clickable_button_Japanese|日本語]]
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.


= A simple clickable button tutorial =
Let's starting by importing the necessary PySide2 classes and python sys module:


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.
<syntaxhighlight lang="python" line='line'>
import sys
from PySide2.QtWidgets import QApplication, QPushButton                                                                                                                                                                                                                                                                 
</syntaxhighlight>


Let's starting by importing the necessary Qt classes and python sys class:
Let's also create a python function which writes the message to the console:


<code><br />import sys<br />from PySide.QtCore import *<br />from PySide.QtGui import *<br /></code>
<syntaxhighlight lang="python" line='line'>
# Greetings
def say_hello():                                                                                   
    print("Button clicked, Hello!")
</syntaxhighlight>


Let's also create a python function which writes &quot;Hello World&amp;quot; to the console:
Now, as mentioned in previous examples you must create the QApplication which will run your PySide2 code:


<code><br /># Greetings<br />def sayHello():<br /> print &quot;Hello World!&quot;<br /></code>
<syntaxhighlight lang="python" line='line'>
# Create the Qt Application
app = QApplication(sys.argv)
</syntaxhighlight>


Now, as mentioned in [[Hello_World_in_PySide|Your first PySide application]], you must create the QApplication which will run your PySide code:
Let's create the clickable button, a QPushButton.
We pass a python string on the constructor which will label the button:


<code><br /># Create the Qt Application<br />app = QApplication(sys.argv)<br /></code>
<syntaxhighlight lang="python" line='line'>
# Create a button
button = QPushButton("Click me")
</syntaxhighlight>


Let's create the clickable button, a QPushButton. We pass a python string on the constructor which will label the button:
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:


<code><br /># Create a button<br />button = QPushButton(&quot;Click me&amp;quot;)<br /></code>
<syntaxhighlight lang="python" line='line'>
# Connect the button to the function
button.clicked.connect(say_hello)
</syntaxhighlight>


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:
Finally, we show the button and start the Qt main loop:
 
<syntaxhighlight lang="python" line='line'>
# Show the button
button.show()
# Run the main Qt loop
app.exec_()
</syntaxhighlight>
 
== Full Code ==
 
<syntaxhighlight lang="python" line='line'>
#!/usr/bin/python
# -'''- coding: utf-8 -'''-
 
import sys                                                                                         
from PySide2.QtWidgets import QApplication, QPushButton                                                                                                                                                                                                                                                                 
                                                                                                   
def say_hello():                                                                                   
print("Button clicked, Hello!")                                                                   
                                                                                                   
# Create the Qt Application                                                                       
app = QApplication(sys.argv)                                                                       
# Create a button, connect it and show it                                                         
button = QPushButton("Click me")                                                                   
button.clicked.connect(say_hello)                                                                   
button.show()                                                                                     
# Run the main Qt loop                                                                             
app.exec_()
</syntaxhighlight>
 
== A button to exit the application ==
Following the same idea, we can create a a QPushButton that closes the application when clicked.
<syntaxhighlight lang="python" line='line'>
from PySide2.QtWidgets import QApplication, QPushButton
 
if __name__ == "__main__":
    # Create a QApplication
    app = QApplication([])
 
    # Create a button
    button = QPushButton('Exit')
 
    # Connect the button "clicked" signal to the exit() method
    # that finishes the QApplication
    button.clicked.connect(app.exit)
 
    button.show()
    app.exec_()
</syntaxhighlight>
 
= Another example =
 
Take a look of the following code,
it follows the same idea previously described but interacting with other python modules
 
<syntaxhighlight lang="python" line='line'>
import sys
import random
from PySide2 import QtCore, QtWidgets, QtGui
 
class MyWidget(QtWidgets.QWidget):
    def __init__(self):
        QtWidgets.QWidget.__init__(self)
 
        self.hello = ["Hallo Welt", "你好,世界", "Hei maailma",
            "Hola Mundo", "Привет мир"]


<code><br /># Connect the button to the function<br />button.clicked.connect(sayHello)<br /></code>
        self.button = QtWidgets.QPushButton("Click me!")
        self.text = QtWidgets.QLabel("Hello World")
        self.text.setAlignment(QtCore.Qt.AlignCenter)
 
        self.layout = QtWidgets.QVBoxLayout()
        self.layout.addWidget(self.text)
        self.layout.addWidget(self.button)
        self.setLayout(self.layout)
 
        self.button.clicked.connect(self.magic)


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


<code><br /># Show the button<br />button.show()<br /># Run the main Qt loop<br />app.exec_()<br /></code>
    def magic(self):
        self.text.setText(random.choice(self.hello))


== Full Code ==


<code><br />#!/usr/bin/python<br /># <s>'''- coding: utf-8 -'''</s>
if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)


import sys<br />from PySide.QtCore import *<br />from PySide.QtGui import *
    widget = MyWidget()
    widget.show()


def sayHello():<br /> print &quot;Hello World!&quot;
    sys.exit(app.exec_())


# Create the Qt Application<br />app = QApplication(sys.argv)
</syntaxhighlight>
# Create a button, connect it and show it<br />button = QPushButton(&quot;Click me&amp;quot;)<br />button.clicked.connect(sayHello)<br />button.show()
# Run the main Qt loop<br />app.exec_()<br /></code>

Latest revision as of 12:44, 11 July 2022

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:

import sys
from PySide2.QtWidgets import QApplication, QPushButton

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

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

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

# Create the Qt Application
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:

# Create a button
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:

# Show the button
button.show()
# Run the main Qt loop
app.exec_()

Full Code

#!/usr/bin/python
# -'''- coding: utf-8 -'''-

import sys                                                                                          
from PySide2.QtWidgets import QApplication, QPushButton                                                                                                                                                                                                                                                                  
                                                                                                    
def say_hello():                                                                                     
 print("Button clicked, Hello!")                                                                    
                                                                                                    
# Create the Qt Application                                                                         
app = QApplication(sys.argv)                                                                        
# Create a button, connect it and show it                                                           
button = QPushButton("Click me")                                                                    
button.clicked.connect(say_hello)                                                                    
button.show()                                                                                       
# Run the main Qt loop                                                                              
app.exec_()

A button to exit the application

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

from PySide2.QtWidgets import QApplication, QPushButton

if __name__ == "__main__":
    # Create a QApplication
    app = QApplication([])

    # Create a button
    button = QPushButton('Exit')

    # Connect the button "clicked" signal to the exit() method
    # that finishes the QApplication
    button.clicked.connect(app.exit)

    button.show()
    app.exec_()

Another example

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

import sys
import random
from PySide2 import QtCore, QtWidgets, QtGui

class MyWidget(QtWidgets.QWidget):
    def __init__(self):
        QtWidgets.QWidget.__init__(self)

        self.hello = ["Hallo Welt", "你好,世界", "Hei maailma",
            "Hola Mundo", "Привет мир"]

        self.button = QtWidgets.QPushButton("Click me!")
        self.text = QtWidgets.QLabel("Hello World")
        self.text.setAlignment(QtCore.Qt.AlignCenter)

        self.layout = QtWidgets.QVBoxLayout()
        self.layout.addWidget(self.text)
        self.layout.addWidget(self.button)
        self.setLayout(self.layout)

        self.button.clicked.connect(self.magic)


    def magic(self):
        self.text.setText(random.choice(self.hello))


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)

    widget = MyWidget()
    widget.show()

    sys.exit(app.exec_())