What happens if you call only setDragDropMode() and not setDefaultDropAction() or setMovement()
It seems this was enough to get everything working!
That is, to get the behaviour I want I just need to call setDragDropMopde(QAbstractItemView::InternalMove). Any call to setDefaultDropAction() or setMovement() interferes somehow. I got confused cause on Win the call to setDefaultDropAction() does not change the overall behaviour (at least nothing I could notice), while on Mac it breaks the d'n'd, making items disappear whenever they are moved.
I also implemented the further suggested fix (no items vector and calls to QListWidget::item).
Here's for future reference the full mainwindow.cpp that works for me
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QBoxLayout>
#include <QDebug>
MainWindow
::MainWindow(QWidget *parent
) , ui(new Ui::MainWindow)
{
ui->setupUi(this);
this->setCentralWidget(w);
w->setLayout(vl);
vl->layout()->addWidget(lw);
// lw->setDefaultDropAction(Qt::MoveAction); REMOVED
// lw->setMovement(QListView::Snap); REMOVED
connect(model,
&QAbstractItemModel
::rowsMoved,
this,
[=] (const QModelIndex &,
int from,
int,
const QModelIndex &,
int to
) {
qDebug() << "moved item from" << from << "to" << to;
});
}
MainWindow::~MainWindow()
{
for (int i = 0; i < lw->count(); i++)
{
qDebug() << lw->item(i)->text();
}
delete ui;
}
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QBoxLayout>
#include <QDebug>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
QWidget * w = new QWidget;
this->setCentralWidget(w);
QVBoxLayout * vl = new QVBoxLayout;
w->setLayout(vl);
lw = new QListWidget;
vl->layout()->addWidget(lw);
lw->setDragDropMode(QAbstractItemView::InternalMove);
// lw->setDefaultDropAction(Qt::MoveAction); REMOVED
// lw->setMovement(QListView::Snap); REMOVED
lw->addItem(new QListWidgetItem("item 1"));
lw->addItem(new QListWidgetItem("item 2"));
lw->addItem(new QListWidgetItem("item 3"));
QAbstractItemModel * model = lw->model();
connect(model, &QAbstractItemModel::rowsMoved, this, [=] (const QModelIndex &, int from, int, const QModelIndex &, int to)
{
qDebug() << "moved item from" << from << "to" << to;
});
}
MainWindow::~MainWindow()
{
for (int i = 0; i < lw->count(); i++)
{
qDebug() << lw->item(i)->text();
}
delete ui;
}
To copy to clipboard, switch view to plain text mode
and of course you need this declaration too in MainWindow's properties:
QListWidget * lw;
To copy to clipboard, switch view to plain text mode
Thank you very much for your help!
Bookmarks