2
votes

I'm trying to make drag and drop inside a tree widget work to be able to move items around inside that widget. I've managed to make items draggable but when I release the mouse button the item disappears. To narrow it down I've tried the following example (taken from another post here on SO) which has the same issues as my tree widget in Qt 5.4 on Windows 7:

#include <QListWidget>

int main(int argc, char **argv)
{
    QApplication a(argc, argv);

    QListWidget lw;

    for(int i = 1; i < 10; ++i)
        lw.addItem(new QListWidgetItem(QString("Item %1").arg(i)));
    lw.setDragEnabled(true); // ***
    lw.viewport()->setAcceptDrops(true); // ***
    lw.setDefaultDropAction(Qt::MoveAction); // ***
    lw.setDropIndicatorShown(true); // ***

    lw.setDragDropMode(QAbstractItemView::InternalMove);

    lw.show();

    a.connect(&a, SIGNAL(lastWindowClosed()), &a, SLOT(quit()));
    a.exec();
}

When I run this code and drag/drop some items it looks like this: dragdrop

Why is the dragged item removed? Any ideas of what I'm missing?

3

3 Answers

3
votes

I have changed one line in your code:

lw.setDefaultDropAction(Qt::TargetMoveAction);

and now it works fine (Qt 5.4.1 Windows 8, Visual Studio 2013).

3
votes

It's a bug in Qt 5.4.1, your code work correctly on Qt 4.8.6

1
votes

With Qt 5.10 or later, you have to call "setMovement(QListView::Free)"

myList->setDragDropMode(QAbstractItemView::InternalMove);
myList->setDefaultDropAction(Qt::TargetMoveAction);
#if QT_VERSION >= QT_VERSION_CHECK(5,10,0)
    myList->setMovement(QListView::Free);
#endif