PyQt5 QListWidget - Setting Drag Drop Property

PyQt5 QListWidget - Setting Drag Drop Property

In PyQt5, QListWidget can be configured to support drag-and-drop operations. This feature is useful for creating interfaces where you can rearrange items in a list or move items between different lists. To enable and configure drag-and-drop in a QListWidget, you need to set the appropriate drag-and-drop properties.

Here's how to set up a QListWidget for drag-and-drop:

1. Import PyQt5 Modules

First, import the necessary modules:

from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QListWidget from PyQt5.QtCore import Qt 

2. Create a Main Window Class

In your main window class, create the QListWidget and configure its drag-and-drop settings:

class MainWindow(QWidget): def __init__(self): super().__init__() self.layout = QVBoxLayout(self) self.listWidget = QListWidget() self.layout.addWidget(self.listWidget) # Populate the list for demonstration purposes for i in range(10): self.listWidget.addItem(f'Item {i + 1}') # Enable drag & drop self.listWidget.setDragDropMode(QListWidget.InternalMove) # Optional: Set the selection mode to enable multiple item dragging self.listWidget.setSelectionMode(QListWidget.ExtendedSelection) 

3. Enable Drag and Drop

The key line here is setting the drag-drop mode:

self.listWidget.setDragDropMode(QListWidget.InternalMove) 

This enables internal drag and drop, where items can be reordered within the QListWidget itself.

4. Initialize and Run the Application

Finally, initialize and run your application:

if __name__ == '__main__': app = QApplication([]) window = MainWindow() window.show() app.exec_() 

Additional Configurations

  • setSelectionMode(QListWidget.ExtendedSelection): This allows multiple items to be selected and dragged together. Other selection modes include SingleSelection, MultiSelection, and ContiguousSelection.
  • setDragEnabled(True): This enables the widget to initiate a drag operation. It's usually enabled by default when setDragDropMode is used.

By setting these properties, you enable drag-and-drop functionality in the QListWidget. Users can now click and drag items within the list to reorder them.


More Tags

dom-manipulation jacoco-maven-plugin encoding angular-router offline identifier qt4 multiple-instances android-camera sendgrid

More Programming Guides

Other Guides

More Programming Examples