Fading Coder

One Final Commit for the Last Sprint

Home > Tools > Content

Implementing List Item Addition, Deletion, and Sorting with PyQt

Tools 2

A QListView widget is used to display items from a QAbstractItemModel. The QStandardItemModel class provides a generic model for storing custom data. This guide demonstrates creating a simple application with a list view that supports adding new items, remoivng the last item, and sorting items alphabetically.

1.1 Creaitng the List View and Model

Initialize a QStandardItemModel with data and assign it to a QListView.

# Initial list data
initial_data = ['Panda A', 'Panda B', 'Panda C', 'Panda D']

# Create a standard item model with 4 rows and 1 column
self.data_model = QStandardItemModel(4, 1)

# Populate the model with the initial data
for index in range(self.data_model.rowCount()):
    list_item = QStandardItem(initial_data[index])
    self.data_model.setItem(index, 0, list_item)

# Insert an additional row after the initial data
self.data_model.insertRow(4, QStandardItem("Panda E"))

# Create the list view and set its model
self.list_display = QListView()
self.list_display.setModel(self.data_model)

1.2 Adding Input and Control Buttons

Create a text input field (QLineEdit) and three buttons (QPushButton) for the operations.

# Text input field for new items
self.input_field = QLineEdit()

# Buttons for operations
self.add_button = QPushButton("Add Item", clicked=self.insert_item)
self.remove_button = QPushButton("Remove Item", clicked=self.delete_item)
self.sort_button = QPushButton("Sort Items", clicked=self.arrange_items)

1.3 Assembling the Layout

Arrange the widgets using QVBoxLayout and QHBoxLayout.

# Horizontal layout for the buttons
button_layout = QHBoxLayout()
button_layout.setContentsMargins(0, 0, 0, 0)
button_layout.addWidget(self.add_button)
button_layout.addWidget(self.remove_button)
button_layout.addWidget(self.sort_button)

# Main vertical layout
main_layout = QVBoxLayout(self)
main_layout.addWidget(self.list_display)
main_layout.addWidget(self.input_field)
main_layout.addLayout(button_layout)

1.4 Applying Custom Styles

Use Qt Style Sheets to customize the appearance of the QListView.

self.list_display.setStyleSheet("""
    QListView {
        background-color: #F5F5F5;
        color: #222222;
        border: 1px solid #AAAAAA;
        font-size: 14px;
    }
    QListView::Item {
        padding: 8px;
        border-bottom: 1px dotted #CCCCCC;
    }
    QListView::Item:hover {
        background-color: #DDDDDD;
        color: #0066CC;
    }
""")

2. Implementing Core Functions

Connect the button signals to slot methods that manipulate the underlying data model.

2.1 Adding an Item

The insert_item method reads text from the input field and appends it as a new row to the model.

def insert_item(self):
    new_text = self.input_field.text().strip()
    if new_text:
        new_item = QStandardItem(new_text)
        self.data_model.appendRow(new_item)
        self.input_field.clear()  # Clear the input field after adding

2.2 Removing an Item

The delete_item method removes the last row from the model.

def delete_item(self):
    total_rows = self.data_model.rowCount()
    if total_rows > 0:
        self.data_model.removeRow(total_rows - 1)

2.3 Sorting Items

The arrange_items method sorts the items in the first column (column 0) in ascending order.

def arrange_items(self):
    self.data_model.sort(0)

3. Complete Application Code

Below is the full source code for a functional PyQt6 application.

import sys
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QStandardItemModel, QStandardItem
from PyQt6.QtWidgets import (QApplication, QWidget, QVBoxLayout,
                             QHBoxLayout, QListView, QLineEdit, QPushButton)


class ListManagerWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("PyQt List Manager")
        self.resize(400, 400)
        self.initialize_ui()

    def initialize_ui(self):
        # 1.1 Setup List and Model
        sample_list = ['Charlie', 'Dexter', 'Bailey', 'Archie']
        self.data_model = QStandardItemModel(4, 1)
        for idx in range(self.data_model.rowCount()):
            item = QStandardItem(sample_list[idx])
            self.data_model.setItem(idx, 0, item)
        self.data_model.insertRow(4, QStandardItem("Zoe"))

        self.list_display = QListView()
        self.list_display.setModel(self.data_model)

        # 1.2 Setup Input and Buttons
        self.input_field = QLineEdit()
        self.input_field.setPlaceholderText("Enter new item text")

        self.add_button = QPushButton("Add Item", clicked=self.insert_item)
        self.remove_button = QPushButton("Remove Last", clicked=self.delete_item)
        self.sort_button = QPushButton("Sort A-Z", clicked=self.arrange_items)

        # 1.3 Setup Layouts
        control_layout = QHBoxLayout()
        control_layout.addWidget(self.add_button)
        control_layout.addWidget(self.remove_button)
        control_layout.addWidget(self.sort_button)

        main_layout = QVBoxLayout(self)
        main_layout.addWidget(self.list_display)
        main_layout.addWidget(self.input_field)
        main_layout.addLayout(control_layout)

        # 1.4 Apply Styling
        self.apply_styling()

    def apply_styling(self):
        self.list_display.setStyleSheet("""
            QListView {
                background-color: #FAFAFA;
                color: #333;
                border: 2px solid #C0C0C0;
                border-radius: 5px;
                font-family: Arial;
            }
            QListView::Item {
                padding: 10px;
            }
            QListView::Item:selected {
                background-color: #B0D0FF;
            }
            QListView::Item:hover {
                background-color: #E8E8E8;
            }
        """)

    # 2.1 Add Item Function
    def insert_item(self):
        text_content = self.input_field.text().strip()
        if text_content:
            self.data_model.appendRow(QStandardItem(text_content))
            self.input_field.clear()

    # 2.2 Delete Item Function
    def delete_item(self):
        current_row_count = self.data_model.rowCount()
        if current_row_count > 0:
            self.data_model.removeRow(current_row_count - 1)

    # 2.3 Sort Item Function
    def arrange_items(self):
        self.data_model.sort(0, Qt.SortOrder.AscendingOrder)


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

Related Articles

Efficient Usage of HTTP Client in IntelliJ IDEA

IntelliJ IDEA incorporates a versatile HTTP client tool, enabling developres to interact with RESTful services and APIs effectively with in the editor. This functionality streamlines workflows, replac...

Installing CocoaPods on macOS Catalina (10.15) Using a User-Managed Ruby

System Ruby on macOS 10.15 frequently fails to build native gems required by CocoaPods (for example, ffi), leading to errors like: ERROR: Failed to build gem native extension checking for ffi.h... no...

Resolve PhpStorm "Interpreter is not specified or invalid" on WAMP (Windows)

Symptom PhpStorm displays: "Interpreter is not specified or invalid. Press ‘Fix’ to edit your project configuration." This occurs when the IDE cannot locate a valid PHP CLI executable or when the debu...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.