[Python] QListWidget drag and drop configuration: When to use the mode instead of the...

Discussão em 'Python' iniciado por Stack, Maio 5, 2025.

  1. Stack

    Stack Membro Participativo

    I'm learning how to setup drag and drop in the view-model framework description at Qt site. When applied to convenience views (QListWidget, QTableWidget, QTreeWidget), the documentation uses either (in original C++ version):

    listWidget->setDragEnabled(true);
    listWidget->viewport()->setAcceptDrops(true);


    or:

    listWidget->setDragDropMode(QAbstractItemView::InternalMove);


    I'm unable to figure out whether setDragDropMode is a shortcut to set individual properties of the widget and which ones in addition of the two above, or it actually does more. I see using QAbstractItemView::InternalMove and QAbstractItemView::DragDrop both set DragEnabled and setAcceptDrops to true, but lead to a different behavior for the item (move vs. copy), so I know there is more behind the mode method. I would like to clarify this point in order to know when to use the mode method.

    My questions:

    • Are the two approaches equivalent?
    • Which properties/attributes are actually set by the mode method?
    • What are the use cases for each one?

    I use Qt for Python if that matters.


    As an example, if I create a list widget with each approach, it seems the result is perfectly equivalent (in this specific case):

    from qtpy.QtWidgets import (QApplication, QWidget, QListWidget, QHBoxLayout)

    class Window(QWidget):

    texts = ['Sycamore', 'Chestnut', 'Walnut', 'Mahogany']

    def __init__(self):
    super().__init__()

    lw_1 = QListWidget()
    lw_1.addItems(self.texts)
    self.print_props('When created', lw_1)

    lw_2 = QListWidget()
    lw_2.addItems(self.texts)

    # Comparing
    lw_1.setDragEnabled(True)
    lw_1.viewport().setAcceptDrops(True)
    lw_1.setDropIndicatorShown(True)
    self.print_props('Using properties', lw_1)

    # With
    mode = lw_2.DragDrop
    lw_2.setDragDropMode(mode)
    self.print_props(f'Using mode ({mode})', lw_2)

    layout = QHBoxLayout(self)
    layout.addWidget(lw_1)
    layout.addWidget(lw_2)

    def print_props(self, text, widget):
    print()
    print(text)
    print('drag:', widget.dragEnabled())
    print('drop:', widget.viewport().acceptDrops())
    print('mode:', widget.dragDropMode())


    def main():
    app = QApplication([])
    window = Window()
    window.show()
    app.exec()

    main()

    Continue reading...

Compartilhe esta Página