PDA

View Full Version : Drag items in QListWidget while the mouse left button is pressed



sargeslash
8th March 2013, 13:09
I am having trouble with the dragging of items inside a QListWidget, the items which are selected are stuck with the mouse cursor even after the mouse button is released. I want to reorder the items inside the QListWidget by dragging them though mouse while the mouse left button is pressed.
I have promoted my ui->listwidget to a custom listwidget to accept drag and drops.



#ifndef PROJECTLISTWIDGET_H
#define PROJECTLISTWIDGET_H

class ProjectListWidget : public QListWidget
{
Q_OBJECT
public:
ProjectListWidget(QWidget *parent = 0);

signals:
void itemDrag();

protected:
void mousePressEvent(QMouseEvent *event);
void mouseMoveEvent(QMouseEvent *event);
void dragEnterEvent(QDragEnterEvent *event);
void dragMoveEvent(QDragMoveEvent *event);
void dropEvent(QDropEvent *event);
void performDrag();
QPoint startPos;
};


#endif // PROJECTLISTWIDGET_H



#include "projectlistwidget.h"

using namespace std;

ProjectListWidget::ProjectListWidget(QWidget *parent)
: QListWidget(parent)
{
setAcceptDrops(true);
setDragEnabled(true);
}

void ProjectListWidget::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton)
{
startPos = event->pos();
}
QListWidget::mousePressEvent(event);

}

void ProjectListWidget::mouseMoveEvent(QMouseEvent *event)
{
if (event->buttons() & Qt::LeftButton)
{
int distance = (event->pos() - startPos).manhattanLength();
if (distance >= QApplication::startDragDistance())
{
performDrag();
}
}
QListWidget::mouseMoveEvent(event);
}

void ProjectListWidget::performDrag()
{
QListWidgetItem *item = currentItem();
if (item) {
QMimeData *mimeData = new QMimeData;
mimeData->setText(item->text());
QDrag *drag = new QDrag(this);
drag->setMimeData(mimeData);
emit itemDrag();
if (drag->exec(Qt::MoveAction) == Qt::CopyAction)
delete item;
}
}

void ProjectListWidget::dragEnterEvent(QDragEnterEvent *event)
{
if (event->mimeData()->hasUrls())
{
event->acceptProposedAction();
} else
{
QListWidget::dragEnterEvent(event);
}
}

void ProjectListWidget::dragMoveEvent(QDragMoveEvent *event)
{
if (event->mimeData()->hasUrls() & Qt::LeftButton)
{
event->acceptProposedAction();
} else
{
QListWidget::dragMoveEvent(event);
}
}

void ProjectListWidget::dropEvent(QDropEvent *event)
{
if (event->mimeData()->hasUrls())
{
QList<QUrl> urls = event->mimeData()->urls();
if (!urls.isEmpty())
{
QUrl url;
foreach (url,urls)
{
new QListWidgetItem(url.toLocalFile(),this);
emit itemDrag();
}
}
event->acceptProposedAction();
}
QListWidget::dropEvent(event);
}




8803

wysota
10th March 2013, 17:40
Why don't you just use the QAbstractItemView::dragDropMode property?