Basic Widgets in PyQt6

As a PyQt developer with experience in creating desktop applications, I have worked extensively with various widgets and configurations. I am excited to share my knowledge about the fundamental widgets in PyQt6 that form the building blocks of any modern desktop application. Let us get into the topic of PyQt6 widgets and explore how can we use them.

What is PyQt6?

PyQt6 is the latest version of PyQt, a set of Python bindings for The Qt Company’s Qt application framework. Released in 2021, PyQt6 brings modern GUI capabilities to Python developers, allowing us to create cross-platform applications that run seamlessly on Windows, macOS, and Linux.

Before getting into the widgets, let’s make sure we have PyQt6 installed:

# Install PyQt6 using pip
pip install PyQt6

Now, let’s explore the essential widgets that will become your toolkit for application development.

Read Create a Basic Window in PyQt6

1. QLabel: The Foundation of Text Display

QLabel is one of the simplest yet most frequently used widgets in PyQt6. I use it whenever I need to display text or images that users don’t need to interact with.

Basic Implementation of QLabel

import sys
from PyQt6.QtWidgets import QApplication, QLabel, QWidget
from PyQt6.QtCore import Qt

class SimpleWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("My First PyQt6 Application")
        self.setGeometry(100, 100, 400, 200)

        # Creating a simple label
        self.label = QLabel("Welcome to PyQt6!", self)
        self.label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.label.setStyleSheet("font-size: 24px; color: #0066cc;")

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

You can see the output in the screenshot below.

Widgets in PyQt6

Key Methods for QLabel

MethodDescription
setText()Changes the text displayed in the label
setPixmap()Displays an image instead of text
setAlignment()Controls how content is aligned
setWordWrap()Enables/disables text wrapping
linkActivatedSignal emitted when a user clicks a hyperlink

Check out QComboBox Widget in PyQt6

2. QPushButton: Interactive User Control

Buttons are essential for user interaction. In my applications, I use QPushButton to initiate actions, submit forms, or navigate between different sections of the application.

Create Responsive Buttons

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

class ButtonExample(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Button Example")
        self.setGeometry(100, 100, 300, 200)

        # Create a layout
        layout = QVBoxLayout()

        # Create a button
        self.button = QPushButton("Click Me!", self)
        self.button.clicked.connect(self.on_button_click)

        # Add button to layout
        layout.addWidget(self.button)
        self.setLayout(layout)

    def on_button_click(self):
        self.button.setText("Button Clicked!")
        self.button.setStyleSheet("background-color: #4CAF50; color: white;")

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

You can see the output in the screenshot below.

Basic Widgets in PyQt6

QPushButton Features

  • Checkable Buttons: Create toggle buttons with setCheckable(True)
  • Default and Auto-Default: Set a button as the default action with setDefault(True)
  • Icons: Add visual elements with setIcon()
  • Shortcuts: Assign keyboard shortcuts with setShortcut()

Read Create a Random Number Generator with QLCDNumber in PyQt6

3. QLineEdit: User Input Made Simple

For collecting user input, QLineEdit is my go-to widget. Whether I’m building a login screen for a healthcare application in Boston or a search feature for a retail system in Chicago, QLineEdit provides a seamless text input experience.

Basic Implementation

from PyQt6.QtWidgets import QApplication, QWidget, QLineEdit, QVBoxLayout, QLabel
import sys

class InputExample(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Input Example")
        self.setGeometry(100, 100, 300, 150)

        # Create layout
        layout = QVBoxLayout()

        # Create label and input
        self.label = QLabel("Enter your name:")
        self.input = QLineEdit()
        self.input.setPlaceholderText("John Smith")
        self.input.textChanged.connect(self.text_changed)

        # Add widgets to layout
        layout.addWidget(self.label)
        layout.addWidget(self.input)
        self.setLayout(layout)

    def text_changed(self, text):
        if text:
            self.label.setText(f"Hello, {text}!")
        else:
            self.label.setText("Enter your name:")

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

You can see the output in the screenshot below.

QLineEdit Widgets in PyQt6

QLineEdit Methods and Properties

Method/PropertyPurpose
setText()Set the text content programmatically
text()Get the current text content
setEchoMode()Control how text is displayed (useful for passwords)
setMaxLength()Limit the number of characters
setReadOnly()Make the field non-editable
setPlaceholderText()Add helper text when field is empty

Check out Build a Simple Digital Clock with QLCDNumber in PyQt6

4. QCheckBox: Boolean Input Options

QCheckBox widgets are perfect for yes/no or true/false options in your applications. I frequently use them in settings screens or preference dialogs.

QCheckBox Implementation

from PyQt6.QtWidgets import QApplication, QWidget, QCheckBox, QVBoxLayout, QLabel
import sys

class CheckboxExample(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Checkbox Example")
        self.setGeometry(100, 100, 300, 150)

        # Create layout
        layout = QVBoxLayout()

        # Create checkbox
        self.checkbox = QCheckBox("Subscribe to newsletter", self)
        self.checkbox.stateChanged.connect(self.state_changed)

        # Create label for status
        self.status = QLabel("Not subscribed")

        # Add widgets to layout
        layout.addWidget(self.checkbox)
        layout.addWidget(self.status)
        self.setLayout(layout)

    def state_changed(self, state):
        if state:
            self.status.setText("You are now subscribed!")
            self.status.setStyleSheet("color: green;")
        else:
            self.status.setText("Not subscribed")
            self.status.setStyleSheet("color: red;")

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

You can see the output in the screenshot below.

QCheckBox Widgets in PyQt6

5. QComboBox: Dropdown Selection Made Easy

QComboBox (dropdown) is an efficient user interface element for selecting one option from many. I implement it in almost all of my applications.

QComboBox Example

from PyQt6.QtWidgets import QApplication, QWidget, QComboBox, QVBoxLayout, QLabel
import sys

class ComboBoxExample(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("State Selector")
        self.setGeometry(100, 100, 350, 200)

        # Create layout
        layout = QVBoxLayout()

        # Create label
        self.label = QLabel("Select your state:")

        # Create combo box
        self.combo = QComboBox()
        self.combo.addItems(["California", "Texas", "New York", "Florida", "Illinois"])
        self.combo.currentTextChanged.connect(self.selection_changed)

        # Result label
        self.result = QLabel("")

        # Add widgets to layout
        layout.addWidget(self.label)
        layout.addWidget(self.combo)
        layout.addWidget(self.result)
        self.setLayout(layout)

    def selection_changed(self, text):
        state_info = {
            "California": "Sacramento is the capital",
            "Texas": "Austin is the capital",
            "New York": "Albany is the capital",
            "Florida": "Tallahassee is the capital",
            "Illinois": "Springfield is the capital"
        }

        self.result.setText(state_info.get(text, ""))

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

Key QComboBox Methods

  • addItem/addItems: Add one or multiple items to the dropdown
  • currentText/currentIndex: Get the selected item as text or its position
  • setEditable: Allow users to enter custom values
  • clear: Remove all items from the dropdown
  • count: Get the number of items in the dropdown

Check out QSpinBox Widget in PyQt6

6. QRadioButton: Exclusive Selection

When users need to select exactly one option from a group, QRadioButton is my preferred widget. It’s particularly useful for settings where options are mutually exclusive.

QRadioButton Implementation

from PyQt6.QtWidgets import (QApplication, QWidget, QRadioButton, 
                            QVBoxLayout, QLabel, QButtonGroup)
import sys

class RadioButtonExample(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Payment Method")
        self.setGeometry(100, 100, 300, 200)

        # Create layout
        layout = QVBoxLayout()

        # Create label
        self.label = QLabel("Select your payment method:")
        layout.addWidget(self.label)

        # Create button group for exclusive selection
        self.button_group = QButtonGroup(self)

        # Create radio buttons
        payment_methods = ["Credit Card", "PayPal", "Bank Transfer", "Apple Pay"]
        self.radio_buttons = []

        for i, method in enumerate(payment_methods):
            radio = QRadioButton(method)
            self.radio_buttons.append(radio)
            layout.addWidget(radio)
            self.button_group.addButton(radio, i)

        # Default selection
        self.radio_buttons[0].setChecked(True)

        # Connect signal
        self.button_group.buttonClicked.connect(self.on_button_clicked)

        # Selection result
        self.result = QLabel("Selected: Credit Card")
        layout.addWidget(self.result)

        # Set layout
        self.setLayout(layout)

    def on_button_clicked(self, button):
        self.result.setText(f"Selected: {button.text()}")

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

7. QSlider: Visual Range Selection

For selecting a value from a continuous range, QSlider provides an intuitive interface that I implement in applications requiring numerical input within boundaries.

import sys
from PyQt6.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel, QSlider
from PyQt6.QtCore import Qt

class SliderExample(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("QSlider Example")
        self.setGeometry(100, 100, 300, 150)

        # Layout
        layout = QVBoxLayout()

        # Label to display the value
        self.label = QLabel("Selected Value: 0", self)

        # QSlider
        self.slider = QSlider(Qt.Orientation.Horizontal)
        self.slider.setMinimum(0)
        self.slider.setMaximum(100)
        self.slider.setValue(0)
        self.slider.setTickPosition(QSlider.TickPosition.TicksBelow)
        self.slider.setTickInterval(10)

        # Connect slider value change to function
        self.slider.valueChanged.connect(self.update_label)

        # Add widgets to layout
        layout.addWidget(self.label)
        layout.addWidget(self.slider)
        self.setLayout(layout)

    def update_label(self, value):
        self.label.setText(f"Selected Value: {value}")

# Run the application
app = QApplication(sys.argv)
window = SliderExample()
window.show()
sys.exit(app.exec())

Key Methods for QSlider

MethodDescription
setMinimum(int)Sets the minimum value of the slider.
setMaximum(int)Sets the maximum value of the slider.
setValue(int)Sets the current value of the slider.
valueChanged()Signal emitted when the slider value changes.
setTickPosition(QSlider.TickPosition)Defines the position of tick marks (above, below, or none).
setTickInterval(int)Sets the interval for tick marks.
setOrientation(Qt.Orientation)Sets the slider orientation (Horizontal or Vertical).
setSingleStep(int)Defines how much the value changes with each key press.
setPageStep(int)Defines the step size when the user moves the slider using PageUp/PageDown.
sliderMoved()The signal is emitted when the user moves the slider.
These methods allow QSlider to be full customizable for various user interactions.

Read QCheckBox Widget in PyQt6

8. QTextEdit: Multi-Line Text Input

QTextEdit is a useful widget for handling multi-line text input and display. I use it when I need to implement a text editor or allow users to input formatted text.

Basic Implementation of QTextEdit

import sys
from PyQt6.QtWidgets import QApplication, QTextEdit, QWidget, QVBoxLayout

class TextEditor(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("QTextEdit Example")
        self.setGeometry(100, 100, 400, 300)

        self.text_edit = QTextEdit(self)
        self.text_edit.setPlaceholderText("Type something here...")

        layout = QVBoxLayout()
        layout.addWidget(self.text_edit)
        self.setLayout(layout)

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

Key Methods for QTextEdit

MethodDescription
setText(str)Sets the text in the QTextEdit field.
append(str)Adds text to the end of the existing content.
clear()Clears all text from the QTextEdit.
toPlainText()Returns the current text as plain text.
setReadOnly(bool)Enables/disables editing mode.
setHtml(str)Sets formatted text using HTML.
undo()Reverts the last text change.
redo()Restores the undone change.

Check out QRadioButton Widget in PyQt6

9. QListWidget: Displaying Lists of Items

QListWidget is used when I need to display a list of selectable items, making it great for file explorers, option lists, and task managers.

Basic Implementation of QListWidget

import sys
from PyQt6.QtWidgets import QApplication, QListWidget, QWidget, QVBoxLayout

class ListExample(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("QListWidget Example")
        self.setGeometry(100, 100, 300, 200)

        self.list_widget = QListWidget(self)
        self.list_widget.addItems(["Apple", "Banana", "Cherry", "Date"])

        layout = QVBoxLayout()
        layout.addWidget(self.list_widget)
        self.setLayout(layout)

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

Key Methods for QListWidget

MethodDescription
addItem(str)Adds a single item to the list.
addItems(list)Adds multiple items to the list.
clear()Removes all items from the list.
currentItem()Returns the currently selected item.
takeItem(int)Removes an item at the specified index.
row(QListWidgetItem)Gets the row number of an item.

10. QTableWidget: Displaying Tables

QTableWidget provides a simple way to create and manage tables in PyQt6 applications. I use it to present structured data with rows and columns.

Basic Implementation of QTableWidget

import sys
from PyQt6.QtWidgets import QApplication, QTableWidget, QTableWidgetItem, QWidget, QVBoxLayout

class TableExample(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("QTableWidget Example")
        self.setGeometry(100, 100, 400, 300)

        self.table = QTableWidget(3, 2, self)  # 3 rows, 2 columns
        self.table.setItem(0, 0, QTableWidgetItem("John"))
        self.table.setItem(0, 1, QTableWidgetItem("25"))

        layout = QVBoxLayout()
        layout.addWidget(self.table)
        self.setLayout(layout)

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

Key Methods for QTableWidget

MethodDescription
setRowCount(int)Sets the number of rows.
setColumnCount(int)Sets the number of columns.
setItem(row, col, QTableWidgetItem)Inserts an item at a specific row and column.
clearContents()Clears the table data but keeps the structure.
selectedItems()Returns selected table items.

Check out Handle Button Click Events Using Signals and Slots in PyQt6

11. QSpinBox: Numeric Input

QSpinBox is used for selecting integer values with up/down controls. I use it when a user needs to input numerical data with fixed increments.

Basic Implementation of QSpinBox

import sys
from PyQt6.QtWidgets import QApplication, QSpinBox, QWidget, QVBoxLayout

class SpinBoxExample(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("QSpinBox Example")
        self.setGeometry(100, 100, 300, 100)

        self.spin_box = QSpinBox(self)
        self.spin_box.setRange(0, 100)
        self.spin_box.setValue(10)

        layout = QVBoxLayout()
        layout.addWidget(self.spin_box)
        self.setLayout(layout)

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

Key Methods for QSpinBox

MethodDescription
setRange(min, max)Sets the minimum and maximum value.
setValue(int)Sets the current value.
valueChanged()Signal emitted when value changes.

12. QProgressBar: Visualizing Progress

QProgressBar is useful when I want to indicate progress for tasks like file downloads or processing operations.

Basic Implementation of QProgressBar

import sys
from PyQt6.QtWidgets import QApplication, QProgressBar, QWidget, QVBoxLayout

class ProgressExample(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("QProgressBar Example")
        self.setGeometry(100, 100, 300, 100)

        self.progress_bar = QProgressBar(self)
        self.progress_bar.setValue(50)

        layout = QVBoxLayout()
        layout.addWidget(self.progress_bar)
        self.setLayout(layout)

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

Key Methods for QProgressBar

MethodDescription
setValue(int)Sets the current progress value.
setMinimum(int)Sets the minimum progress value.
setMaximum(int)Sets the maximum progress value.

Read Arrange Widgets Using QGridLayout in PyQt6

13. QDialog: Popup Windows

QDialog is used to create pop-up windows for user interactions.

Basic Implementation of QDialog

import sys
from PyQt6.QtWidgets import QApplication, QDialog, QPushButton, QVBoxLayout

class DialogExample(QDialog):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("QDialog Example")

        self.button = QPushButton("Close", self)
        self.button.clicked.connect(self.close)

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

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

Key Methods for QDialog

MethodDescription
exec()Displays the dialog as a modal window.
accept()Closes the dialog and returns Accepted.

14. QMessageBox: Displaying Messages

QMessageBox is a convenient way to show alerts, warnings, and confirmation dialogs.

Basic Implementation of QMessageBox

from PyQt6.QtWidgets import QMessageBox, QApplication

app = QApplication([])
msg = QMessageBox()
msg.setText("This is an alert message!")
msg.exec()

Key Methods for QMessageBox

MethodDescription
setText(str)Sets the message text.
exec()Displays the message box.

Conclusion

In this tutorial, I explained basic widgets in PyQt6. I discussed basic widgets such as QLabel, QPushButton, QLineEdit, QCheckBox, QComboBox, QRadioButton, QSlider, QTextEdit, QListWidget, QTableWidget, QSpinBox, QProgressBar, QDialog, and QMessageBox.

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.