QPushButton is a standard clickable button widget commonly used in applications.
Example usage:
button = QPushButton("Click me")
button.clicked.connect(some_function)
Common Methods:
setText(text: str)
: Sets button text.text() -> str
: Retrieves the current button text.setIcon(icon: QIcon)
: Sets an icon on the button.setEnabled(bool)
: Enables/disables the button.setCheckable(bool)
: Makes the button toggleable.setChecked(bool)
: Checks/unchecks the button (if toggleable).
Signals:
.clicked
.pressed
.released
.toggled(bool)
Exercises
Click on the black triangle on the left of the Exercise name to show the solution.
Exercise 1: Simple Click Counter
Objective:
Create a PySide6 GUI with a single QPushButton
. Every time the button is clicked, a counter should increment, and the updated click count should appear as button text.
Initial Button Text: "Clicks: 0"
Example Output:
After 1st click → “Clicks: 1”
After 2nd click → “Clicks: 2”
After 3rd click → “Clicks: 3”
import sys
from PySide6.QtWidgets import QApplication, QWidget, QPushButton, QLabel, QVBoxLayout
class SimpleClickCounter(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle('Simple Click Counter')
self.resize(400, 400)
self.count = 0
self.count_label = QLabel()
self.count_label.setText('Clicks: 0')
self.count_button = QPushButton('Click Me!')
self.count_button.clicked.connect(self.count_clicks)
self.reset_button = QPushButton('Reset')
self.reset_button.clicked.connect(self.reset_count)
main_layout = QVBoxLayout()
main_layout.addWidget(self.count_label)
main_layout.addWidget(self.count_button)
main_layout.addWidget(self.reset_button)
self.setLayout(main_layout)
def count_clicks(self):
self.count += 1
self.count_label.setText(f'Clicks: {self.count}')
def reset_count(self):
self.count = 0
self.count_label.setText('Clicks: 0')
if __name__ == '__main__':
app = QApplication(sys.argv)
window = SimpleClickCounter()
window.show()
app.exec()
Exercise 2: Toggle Button Color
Objective:
Create a PySide6 GUI with a single toggleable QPushButton
. When clicked, the button toggles between two background colors: Green (checked) and Red (unchecked).
Hints:
Use the methods setCheckable(True)
and handle the toggled
signal.
Use setStyleSheet()
to change the button’s background color.
Initial Button Text: "Toggle Color"
import sys
from PySide6.QtWidgets import QApplication, QWidget, QPushButton, QHBoxLayout
class ToggleButtonColor(QPushButton):
def __init__(self):
super().__init__()
self.setWindowTitle('Toggle Color')
self.setGeometry(300, 300, 300, 300)
self.button = QPushButton('Toggle Color')
self.button.setStyleSheet('background-color:white')
self.button.setCheckable(True)
self.button.toggled.connect(self.change_color)
main_layout = QHBoxLayout()
main_layout.addWidget(self.button)
self.setLayout(main_layout)
def change_color(self, checked):
if checked:
self.button.setStyleSheet('background-color: green; color: white')
else:
self.button.setStyleSheet('background-color: white; color: black')
if __name__ == '__main__':
app = QApplication(sys.argv)
window = ToggleButtonColor()
window.show()
app.exec()
Exercise 3: Enable/Disable Button with Another Button
Objective:
Create a PySide6 GUI with two buttons:
Button 1: "Click Me"
(initially enabled)
Button 2: "Enable/Disable Button"
When you click "Enable/Disable Button"
, it should toggle the enabled state of "Click Me"
.
Hints:
Use the method .setEnabled(bool)
on the first button.
Handle the .clicked
signal on the second button.
import sys
from PySide6.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout
class EnableDisableButton(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle('Enable/Disable button')
self.resize(400, 400)
self.button_click_me = QPushButton('Click me')
self.button_click_me.setEnabled(True)
self.button_enable_disable = QPushButton('Enable/Disable')
self.button_enable_disable.clicked.connect(self.toggle_enable)
main_layout = QVBoxLayout()
main_layout.addWidget(self.button_click_me)
main_layout.addWidget(self.button_enable_disable)
self.setLayout(main_layout)
def toggle_enable(self):
current_state = self.button_click_me.isEnabled()
self.button_click_me.setEnabled(not current_state)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = EnableDisableButton()
window.show()
app.exec()
Exercise 4: QPushButton with Icon Toggle
Objective:
Create a PySide6 GUI with one toggleable button. Clicking the button changes the displayed icon between two different icons (e.g., play ▶️ and pause ⏸️).
Initial Button Text: "Play/Pause"
Hints:
Use setCheckable(True)
and handle the toggled
signal.
Use setIcon(QIcon("icon.png"))
to set the button icon.
Prepare two icon images (e.g., "play.png"
, "pause.png"
).
import sys
from PySide6.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout
from PySide6.QtGui import QIcon
class IconToggle(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("Icon Toggle")
self.resize(400, 400)
self.button = QPushButton("Play/Pause")
self.button.setCheckable(True)
self.button.setIcon(QIcon("play.png"))
self.button.toggled.connect(self.toggle_icon)
main_layout = QVBoxLayout()
main_layout.addWidget(self.button)
self.setLayout(main_layout)
def toggle_icon(self):
if self.button.isChecked():
self.button.setIcon(QIcon("pause.png"))
else:
self.button.setIcon(QIcon("play.png"))
if __name__ == "__main__":
app = QApplication(sys.argv)
window = IconToggle()
window.show()
app.exec()
Exercise 5: Button Click Changes Window Title
Objective:
Create a PySide6 GUI with a single QPushButton
. Each click of the button updates the main window title with a randomly chosen greeting from a predefined list.
Greetings List:
greetings = ["Hello!", "Bonjour!", "Hola!", "Ciao!", "Konnichiwa!"]
Hints:
Import and use random.choice()
from Python’s random
module.
Use the button’s .clicked
signal to trigger the title change.
import sys
from PySide6.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout
import random
class ButtonClickChangesWindowTitle(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("Button Click Changes Window Title")
self.resize(600, 300)
self.button = QPushButton("Change Window Title")
self.button.clicked.connect(self.change_window_title)
main_layout = QVBoxLayout()
main_layout.addWidget(self.button)
self.setLayout(main_layout)
def change_window_title(self):
greetings = ["Hello!", "Bonjour!", "Hola!", "Ciao!", "Konnichiwa!"]
current_greeting = random.choice(greetings)
self.setWindowTitle(current_greeting)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = ButtonClickChangesWindowTitle()
window.show()
app.exec()
Exercise 6: Change Button Text on Click
Objective: Create a GUI with a single QPushButton
. Each time it’s clicked, the button’s text should alternate between "Start"
and "Stop"
.
Initial Button Text: "Start"
import sys
from PySide6.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout
class ChangeButtonText(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle('Change button text')
self.resize(400, 400)
self.button = QPushButton('Start')
self.button.setCheckable(True)
self.button.toggled.connect(self.change_button_text)
main_layout = QVBoxLayout()
main_layout.addWidget(self.button)
self.setLayout(main_layout)
def change_button_text(self, check):
if check:
self.button.setText('Stop')
else:
self.button.setText('Start')
if __name__ == '__main__':
app = QApplication(sys.argv)
window = ChangeButtonText()
window.show()
app.exec()
Exercise 7: Resize Button on Click
Objective: Create a GUI with a QPushButton that grows in width by 20 pixels each time it’s clicked, up to a maximum width of 200 pixels. After reaching 200 pixels, reset its width back to the original size (e.g., 80 pixels).
Initial Button Text: "Grow Button"
import sys
from PySide6.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout
class ResizeButtonOnClick(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle('Resize Button On Click')
self.resize(400, 400)
self.size_of_button = 80
self.button = QPushButton('Grow Button')
self.button.setFixedWidth(self.size_of_button)
self.button.setFixedHeight(30)
self.button.clicked.connect(self.resize_button)
main_layout = QVBoxLayout()
main_layout.addWidget(self.button)
self.setLayout(main_layout)
def resize_button(self, check):
self.size_of_button += 20
if self.size_of_button < 200:
self.button.setFixedWidth(self.size_of_button)
else:
self.button.setFixedWidth(80)
self.size_of_button = 80
if __name__ == '__main__':
app = QApplication(sys.argv)
window = ResizeButtonOnClick()
window.show()
app.exec()
Exercise 8: Disable Button after 5 Clicks
Objective: Create a GUI with a QPushButton. Allow it to be clicked exactly 5 times. After the fifth click, disable the button and change its text to "Disabled"
.
Initial Button Text: "Click Me"
import sys
from PySide6.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout
class DisableButtonAfter5Clicks(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle('Disable button in 5 clicks')
self.resize(400, 400)
self.click_counter = 0
self.button = QPushButton('Click Me')
self.button.setEnabled(True)
self.button.clicked.connect(self.disable_click)
main_layout = QVBoxLayout()
main_layout.addWidget(self.button)
self.setLayout(main_layout)
def disable_click(self):
self.click_counter += 1
if self.click_counter == 5:
self.button.setText('Disabled')
self.button.setEnabled(False)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = DisableButtonAfter5Clicks()
window.show()
app.exec()
Exercise 9: Button Tooltip Toggle
Objective: Create a GUI with a toggleable QPushButton. Clicking it should toggle the visibility of a tooltip message saying "I'm a Tooltip!"
.
Initial Button Text: "Show/Hide Tooltip"
Hint:
Use .setToolTip("Tooltip text")
and toggle between an empty and filled tooltip.
import sys
from PySide6.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout
from PySide6.QtCore import QEvent
class ButtonToolTipToggle(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle('Toggle button tooltip')
self.resize(400, 400)
self.button = QPushButton('Show/Hide Tooltip')
self.button.setCheckable(True)
self.button.toggled.connect(self.show_hide_tooltip)
main_layout = QVBoxLayout()
main_layout.addWidget(self.button)
self.setLayout(main_layout)
def show_hide_tooltip(self, checked):
if checked:
self.button.setToolTip('I\'m a tooltip')
else:
self.button.setToolTip('')
QApplication.instance().sendEvent(self.button, QEvent(QEvent.ToolTip))
if __name__ == '__main__':
app = QApplication(sys.argv)
window = ButtonToolTipToggle()
window.show()
app.exec()
Exercise 10: QPushButton Font Size Toggle
Objective: Create a GUI with a QPushButton. Each click toggles its font size between small (12pt) and large (20pt).
Initial Button Text: "Toggle Font Size"
Hint:
Use setFont()
with QFont
to change font size dynamically.
import sys
from PySide6.QtGui import QFont
from PySide6.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout
class ButtonFontSizeToggle(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("Button Font Size Toggle")
self.resize(200, 200)
self.button = QPushButton("Toggle Font Size")
self.button.setCheckable(True)
self.button.toggled.connect(self.change_font_size)
main_layout = QVBoxLayout()
main_layout.addWidget(self.button)
self.setLayout(main_layout)
def change_font_size(self, checked):
if checked:
self.button.setFont(QFont("Arial", 20))
else:
self.button.setFont(QFont("Arial", 12))
if __name__ == "__main__":
app = QApplication(sys.argv)
window = ButtonFontSizeToggle()
window.show()
app.exec()
Expected Outcomes from these exercises:
- Mastery of signals like
.clicked()
and.toggled(bool)
- Understanding of dynamic text and styling changes
- Familiarity with PySide6 methods like
.setEnabled()
,.setToolTip()
,.setFont()
, and.resize()