PDA

View Full Version : Drag and drop in QTreeView with custom QAbstractItem based model



rherzog
13th March 2014, 11:02
Hi folks!

We want to implement drag-drop functionality for our QTreeView which uses a custom QAbstractItem based model.

I've created a QDragableTreeView class which is derived from QTreeView.

The problem is that the implementation works up to the point when the mouse button is released (and the change in order should happen). Infact nothing happens. My question is how can i switch the order of my elements in the tree at the end of the drag?

Header of QDragableTreeView

#ifndef QDRAGABLETREEVIEW_H
#define QDRAGABLETREEVIEW_H

#include <QTreeView>

class QDragableTreeView : public QTreeView
{
Q_OBJECT

void mousePressEvent(QMouseEvent *event);
void mouseMoveEvent(QMouseEvent *event);
void performDrag(void);
void dragEnterEvent ( QDragEnterEvent * event );
void dragMoveEvent(QDragMoveEvent *event);
void dropEvent(QDropEvent *event);


public:
explicit QDragableTreeView(QWidget *parent = 0);


signals:

public slots:

};

#endif // QDRAGABLETREEVIEW_H


PerformDrag implementation:


void QDragableTreeView::performDrag()
{
QModelIndex idx = currentIndex();
PositionsTreeModel *model = static_cast<PositionsTreeModel*>(this->model());
if(model){
qDebug() << "performDrag";
//QStandardItem *sourceItem = model->itemFromIndex(idx);
QMimeData *mimeData = new QMimeData();
mimeData->setText("asdf");

QDrag *drag = new QDrag(this);
drag->setMimeData(mimeData);

if(drag->exec(Qt::MoveAction) == Qt::MoveAction){
//emit layoutAboutToBeChanged();
//model->removeRow(idx.row());
//model->deleteRow(idx);

//emit rowsAboutToBeRemoved(idx.parent(),0,3);
model->removeRow(0, idx);

emit dataChanged(rootIndex(), idx);
qDebug() << "deletingItem...";
qDebug() << "row: " << idx.row();
//emit layoutChanged();
}
}
}


kind regards, reinhart

anda_skoa
13th March 2014, 11:13
One thing that is problematic with the code is that it uses a QModelIndex instance ("idx"), after doing event loop process (call to drag->exec()).

It might be OK dependning on the model, but the correct way to "keep" a model index around is to convert it into a QPersistentModelIndex.

Cheers,
_