How to Create QPushButton Widget in PyQt6?

As a Python developer working on various projects for my clients, I came across a scenario while working on productivity tools for remote teams across America I needed to use the QPushButton widget. In this tutorial, I will explain how to create QPushButton widget in PyQt6 along with suitable examples and screenshots.

Create QPushButton Widget in PyQt6

QPushButton is one of the most fundamental interactive widgets in PyQt6. It creates a clickable button that users can interact with to trigger specific actions in your application. Think of it as the digital equivalent of physical buttons you interact with daily – from elevator buttons to light switches – designed to initiate an action when pressed.

QPushButton offers more customization options and functionality that, when used effectively, can create intuitive and visually appealing user interfaces.

Read Types of Windows in PyQt6

Create Your First QPushButton

Let’s start with the basics – creating a simple button and connecting it to an action:

import sys
from PyQt6.QtWidgets import QApplication, QWidget, QPushButton

class ButtonApp(QWidget):
    def __init__(self):
        super().__init__()
        self.init_ui()

    def init_ui(self):
        # Set up window properties
        self.setWindowTitle("QPushButton Example")
        self.setGeometry(100, 100, 500, 400)
        
        # Create a button
        button = QPushButton("Click Me", self)
        button.move(50, 50)
        button.clicked.connect(self.on_button_click)
        
        self.show()

    def on_button_click(self):
        print("Button clicked!")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = ButtonApp()
    sys.exit(app.exec())

You can see the output in the below screenshot.

Create QPushButton Widget in PyQt6

This creates a button with the text “Click Me” positioned at coordinates (50, 50) from the top-left corner of the window. When clicked, it will print “Button clicked!” to the console.

Check out How to Install PyQt6 on Different Platforms?

Customize Button Appearance

The visual appeal of your buttons plays a crucial role in user experience. Let’s explore various ways to customize QPushButton’s appearance:

Basic Style with setStyleSheet()

import sys
from PyQt6.QtWidgets import QApplication, QWidget, QPushButton

class StyledButtonApp(QWidget):
    def __init__(self):
        super().__init__()
        self.init_ui()

    def init_ui(self):
        self.setWindowTitle("Styled QPushButton Example")
        self.setGeometry(100, 100, 300, 200)  # Set window size

        # Create and style the QPushButton
        styled_button = QPushButton("Styled Button", self)
        styled_button.setGeometry(50, 100, 200, 40)
        styled_button.setStyleSheet("""
            QPushButton {
                background-color: #3498db;
                color: white;
                border-radius: 10px;
                font-size: 16px;
                font-weight: bold;
                padding: 5px;
            }
            QPushButton:hover {
                background-color: #2980b9;
            }
            QPushButton:pressed {
                background-color: #1c6ea4;
            }
        """)

        # Connect button click to an action
        styled_button.clicked.connect(lambda: print("Styled button clicked!"))

        self.show()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = StyledButtonApp()
    sys.exit(app.exec())

You can see the output in the below screenshot.

How to Create QPushButton Widget in PyQt6

Add Icons to Buttons

Icons improve the usability and visual appeal of a GUI application by making buttons more recognizable and user-friendly. PyQt6 allows you to easily add icons to buttons using the QIcon class.

from PyQt6.QtGui import QIcon

icon_button = QPushButton("Save Document", self)
icon_button.setIcon(QIcon("save_icon.png"))
icon_button.setIconSize(QIcon.fromTheme("document-save").actualSize(50, 50))
icon_button.setGeometry(50, 160, 200, 40)
icon_button.clicked.connect(self.save_document)

def save_document(self):
    print("Document saved successfully!")

Change Button Size and Position

When designing a responsive and user-friendly GUI, it is important to correctly size and position buttons. PyQt6 allows you to adjust the dimensions and placement of buttons using the setGeometry() method.

# Different sized buttons
small_button = QPushButton("Small", self)
small_button.setGeometry(50, 220, 100, 30)

medium_button = QPushButton("Medium", self)
medium_button.setGeometry(160, 220, 150, 40)

large_button = QPushButton("Large", self)
large_button.setGeometry(320, 220, 200, 50)

Read Create a Basic Window in PyQt6

Create Different Types of Buttons

PyQt6 supports various button types for different use cases, Let me explain them.

Toggle Buttons

A toggle button is a button that stays pressed when clicked and only returns to its original state when clicked again. This behavior is useful for switching modes, activating/deactivating, etc.

import sys
from PyQt6.QtWidgets import QApplication, QWidget, QPushButton

class ToggleApp(QWidget):
    def __init__(self):
        super().__init__()
        self.init_ui()

    def init_ui(self):
        # Create a toggle button
        self.toggle_button = QPushButton("Toggle Mode", self)
        self.toggle_button.setCheckable(True)  # Make it a toggle button
        self.toggle_button.setGeometry(50, 50, 200, 40)
        self.toggle_button.clicked.connect(self.on_toggle)

        # Window settings
        self.setWindowTitle("Toggle Button Example")
        self.setGeometry(100, 100, 300, 200)
        self.show()

    def on_toggle(self):
        if self.toggle_button.isChecked():
            print("Toggle ON")
            self.toggle_button.setText("Mode: ON")
            self.toggle_button.setStyleSheet("background-color: #27ae60; color: white;")
        else:
            print("Toggle OFF")
            self.toggle_button.setText("Mode: OFF")
            self.toggle_button.setStyleSheet("background-color: #c0392b; color: white;")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = ToggleApp()
    sys.exit(app.exec())

You can see the output in the below screenshot.

Create QPushButton Widget in PyQt6 Toggle Buttons

Default and Auto-Default Buttons

When designing forms or dialogs in PyQt6, it’s common to designate a default button that gets triggered when the Enter key is pressed.

default_button = QPushButton("Submit", self)
default_button.setDefault(True)  # This button is activated when Enter is pressed
default_button.setGeometry(50, 350, 200, 40)
default_button.setStyleSheet("font-weight: bold; background-color: #16a085; color: white;")

This improves usability by allowing users to quickly submit forms without manually clicking the button.

Read QSpinBox Widget in PyQt6

Flat Buttons

Flat buttons are a great way to create a modern, minimalist UI. Unlike standard buttons, flat buttons do not have a raised or 3D effect, making them blend seamlessly into the interface.

flat_button = QPushButton("Flat Style", self)
flat_button.setFlat(True)
flat_button.setGeometry(300, 350, 150, 40)
flat_button.setStyleSheet("""
    QPushButton {
        color: #3498db;
        border: none;
        text-align: left;
        padding-left: 10px;
    }
    QPushButton:hover {
        color: #2980b9;
        text-decoration: underline;
    }
""")

They are often used for toolbar buttons, hyperlinks, and minimalist designs.

Work with Button Signals and Events

PyQt6 provides various signals for QPushButton to handle different types of interactions. This allows developers to respond to user actions efficiently.

multi_signal_button = QPushButton("Interaction Demo", self)
multi_signal_button.setGeometry(50, 410, 200, 50)

# Connect multiple signals
multi_signal_button.clicked.connect(lambda: print("Button clicked!"))
multi_signal_button.pressed.connect(lambda: print("Button pressed down"))
multi_signal_button.released.connect(lambda: print("Button released"))

# You can also differentiate between left and right clicks
multi_signal_button.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
multi_signal_button.customContextMenuRequested.connect(lambda pos: print("Right-clicked"))

Button Events Table

SignalDescriptionCommon Use Case
clickedExecute a function when a button is activatedEmitted when a button is pressed down
pressedEmitted when a button is releasedComplete an action when the button is released
releasedEmitted when a checkable button changes stateStart an action when the button is pressed.
toggledStart an action when the button is pressed beginsUpdate UI based on toggle state

Check out QCheckBox Widget in PyQt6

Create Button Groups

Button groups are useful when you need a set of mutually exclusive buttons, meaning only one button can be selected at a time. This is particularly useful for options like payment methods, quiz answers, or settings selection.

from PyQt6.QtWidgets import QButtonGroup, QHBoxLayout, QVBoxLayout

def create_option_buttons(self):
    # Create a layout for buttons
    layout = QVBoxLayout()

    # Main label
    option_label = QLabel("Select payment method:")
    layout.addWidget(option_label)

    # Horizontal layout for the radio buttons
    h_layout = QHBoxLayout()

    # Create a button group
    self.payment_group = QButtonGroup(self)

    # Create option buttons
    payment_options = ["Credit Card", "PayPal", "Apple Pay", "Bank Transfer"]
    self.option_buttons = []

    for i, option in enumerate(payment_options):
        button = QPushButton(option)
        button.setCheckable(True)  # Make them behave like radio buttons
        self.payment_group.addButton(button, i)  # Add to group with ID
        h_layout.addWidget(button)
        self.option_buttons.append(button)

    # Make first option selected by default
    self.option_buttons[0].setChecked(True)

    # Connect to a slot
    self.payment_group.buttonClicked.connect(self.on_payment_selected)

    layout.addLayout(h_layout)

    # Add a confirmation button
    confirm_button = QPushButton("Confirm Payment Method")
    confirm_button.clicked.connect(self.confirm_payment)
    layout.addWidget(confirm_button)

    # Add the layout to the main window
    main_layout = QVBoxLayout()
    main_layout.addLayout(layout)
    self.setLayout(main_layout)

def on_payment_selected(self, button):
    print(f"Selected payment method: {button.text()}")

def confirm_payment(self):
    selected = self.payment_group.checkedButton()
    if selected:
        print(f"Payment with {selected.text()} confirmed!")

Create Animated Button Effects

For more engaging interfaces, adding animations to your buttons can significantly improve the user experience:

from PyQt6.QtCore import QPropertyAnimation, QEasingCurve, QSize

class AnimatedButton(QPushButton):
    def __init__(self, text, parent=None):
        super().__init__(text, parent)
        self.setStyleSheet("""
            QPushButton {
                background-color: #3498db;
                color: white;
                border-radius: 10px;
                padding: 10px;
            }
            QPushButton:hover {
                background-color: #2980b9;
            }
        """)
        self._animation = QPropertyAnimation(self, b"size")
        self._animation.setDuration(100)
        self._animation.setEasingCurve(QEasingCurve.Type.OutQuad)

    def enterEvent(self, event):
        self._animation.stop()
        self._animation.setStartValue(self.size())
        self._animation.setEndValue(QSize(self.size().width() + 10, self.size().height() + 5))
        self._animation.start()
        super().enterEvent(event)

    def leaveEvent(self, event):
        self._animation.stop()
        self._animation.setStartValue(self.size())
        self._animation.setEndValue(QSize(self.size().width() - 10, self.size().height() - 5))
        self._animation.start()
        super().leaveEvent(event)

# In your main window
animated_button = AnimatedButton("Hover Over Me", self)
animated_button.setGeometry(50, 480, 200, 50)
animated_button.clicked.connect(lambda: print("Animated button clicked!"))

Conclusion

In this tutorial, I explained how to create QPushButton widget in PyQt6. I discussed creating the first QPushButton, customizing button appearance, and creating different types of buttons. I also covered how to work on button signals and events, create button groups, and create animated button effects.

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.