Home » Tutorial on PyQt6 QPushButton

Tutorial on PyQt6 QPushButton

Java SE 11 Programmer II [1Z0-816] Practice Tests
Spring Framework Basics Video Course
Oracle Java Certification
Java SE 11 Developer (Upgrade) [1Z0-817]
Java SE 11 Programmer I [1Z0-815] Practice Tests
1 Year Subscription

QPushButton is one of the most widely used widgets in PyQt6, offering an interactive button that can trigger actions when clicked.

It is versatile and can be customized in appearance and functionality, making it an essential part of any PyQt6 GUI.

In this tutorial, we’ll cover:

1. Basics of QPushButton

To create a QPushButton, instantiate the class, optionally passing the button text or parent widget. Add the button to a layout or a parent widget.

Example: Basic Button Setup

from PyQt6.QtWidgets import QApplication, QPushButton, QMainWindow

def main():
    app = QApplication([])
    window = QMainWindow()
    window.setWindowTitle("Basic QPushButton Example")
    window.setGeometry(100, 100, 300, 200)

    button = QPushButton("Click Me", window)
    button.setGeometry(100, 80, 100, 40)

    window.show()
    app.exec()

if __name__ == "__main__":
    main()

Output:

  • A window with a clickable button labeled “Click Me”.

2. Connecting Buttons to Actions

The clicked signal is emitted when the button is clicked. Connect it to a custom slot (a Python method) to define its behavior.

Example: Connecting Button to a Function

from PyQt6.QtWidgets import QApplication, QPushButton, QMainWindow

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

def main():
    app = QApplication([])
    window = QMainWindow()
    window.setWindowTitle("Button Click Example")
    window.setGeometry(100, 100, 300, 200)

    button = QPushButton("Click Me", window)
    button.setGeometry(100, 80, 100, 40)
    button.clicked.connect(on_button_click)

    window.show()
    app.exec()

if __name__ == "__main__":
    main()

Output:

  • Clicking the button prints Button clicked! to the console.

3. Setting Text and Icons

You can set button text with setText() and display an icon with setIcon().

Example: Button with Text and Icon

from PyQt6.QtWidgets import QApplication, QPushButton, QMainWindow
from PyQt6.QtGui import QIcon

def main():
    app = QApplication([])
    window = QMainWindow()
    window.setWindowTitle("Button with Icon Example")
    window.setGeometry(100, 100, 300, 200)

    button = QPushButton("Save", window)
    button.setGeometry(100, 80, 120, 40)
    button.setIcon(QIcon("path/to/icon.png"))

    window.show()
    app.exec()

if __name__ == "__main__":
    main()

Output:

  • A button labeled “Save” with an icon.

4. Button States (Enabled, Disabled, Checkable)

Disabling a Button

button.setEnabled(False)

Making a Button Checkable

Set the button as checkable to allow toggling between a checked and unchecked state.

button.setCheckable(True)

Example: Checkable Button

from PyQt6.QtWidgets import QApplication, QPushButton, QMainWindow

def on_button_toggle():
    state = "Checked" if button.isChecked() else "Unchecked"
    print(f"Button is now: {state}")

app = QApplication([])
window = QMainWindow()
window.setWindowTitle("Checkable Button Example")
window.setGeometry(100, 100, 300, 200)

button = QPushButton("Toggle Me", window)
button.setGeometry(100, 80, 100, 40)
button.setCheckable(True)
button.clicked.connect(on_button_toggle)

window.show()
app.exec()

Output:

  • The button toggles between “Checked” and “Unchecked” states when clicked.

5. Styling Buttons with CSS

Use setStyleSheet() to style buttons with CSS-like properties.

Example: Custom Button Style

button.setStyleSheet("""
    QPushButton {
        background-color: lightblue;
        border: 2px solid darkblue;
        border-radius: 10px;
        font-size: 16px;
        color: white;
    }
    QPushButton:hover {
        background-color: blue;
    }
    QPushButton:pressed {
        background-color: darkblue;
    }
""")

6. Creating Custom Behavior

You can create buttons with custom actions and add additional signals if necessary.

Example: Button with Custom Behavior

from PyQt6.QtWidgets import QApplication, QPushButton, QMainWindow
from PyQt6.QtCore import QTimer

def on_button_click():
    button.setText("Processing...")
    QTimer.singleShot(2000, lambda: button.setText("Done!"))

app = QApplication([])
window = QMainWindow()
window.setWindowTitle("Custom Button Behavior")
window.setGeometry(100, 100, 300, 200)

button = QPushButton("Start", window)
button.setGeometry(100, 80, 100, 40)
button.clicked.connect(on_button_click)

window.show()
app.exec()

Output:

  • Clicking the button changes its text to “Processing…” for 2 seconds, then updates to “Done!”.

7. Practical Examples

Example 1: Button to Close the Application

from PyQt6.QtWidgets import QApplication, QPushButton, QMainWindow

def main():
    app = QApplication([])
    window = QMainWindow()
    window.setWindowTitle("Close Button Example")
    window.setGeometry(100, 100, 300, 200)

    button = QPushButton("Close", window)
    button.setGeometry(100, 80, 100, 40)
    button.clicked.connect(app.quit)

    window.show()
    app.exec()

if __name__ == "__main__":
    main()

Example 2: Counter Button

from PyQt6.QtWidgets import QApplication, QPushButton, QMainWindow

def on_button_click():
    global count
    count += 1
    button.setText(f"Count: {count}")

app = QApplication([])
window = QMainWindow()
window.setWindowTitle("Counter Button Example")
window.setGeometry(100, 100, 300, 200)

count = 0
button = QPushButton("Count: 0", window)
button.setGeometry(100, 80, 100, 40)
button.clicked.connect(on_button_click)

window.show()
app.exec()

Output:

  • Clicking the button increments a counter displayed on the button.

Example 3: Multiple Buttons with Different Actions

from PyQt6.QtWidgets import QApplication, QPushButton, QMainWindow

def say_hello():
    print("Hello!")

def say_goodbye():
    print("Goodbye!")

app = QApplication([])
window = QMainWindow()
window.setWindowTitle("Multiple Buttons Example")
window.setGeometry(100, 100, 300, 200)

button1 = QPushButton("Hello", window)
button1.setGeometry(50, 80, 100, 40)
button1.clicked.connect(say_hello)

button2 = QPushButton("Goodbye", window)
button2.setGeometry(150, 80, 100, 40)
button2.clicked.connect(say_goodbye)

window.show()
app.exec()

Output:

  • Clicking “Hello” prints Hello! and clicking “Goodbye” prints Goodbye!.

Summary

In this tutorial, we covered:

  1. Basics of QPushButton: Creating buttons and adding them to a layout.
  2. Connecting to Actions: Using signals to handle button clicks.
  3. Text and Icons: Customizing button labels and icons.
  4. Button States: Enabling, disabling, and making buttons checkable.
  5. Styling with CSS: Enhancing appearance with custom styles.
  6. Custom Behavior: Adding unique functionality to buttons.
  7. Practical Examples: Real-world use cases like counters and application exit buttons.

QPushButton is a cornerstone of interactive PyQt6 applications, and its customization options make it highly versatile. Mastering it will greatly enhance your ability to create user-friendly interfaces.

 

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More