0
votes

I'm trying to add the Drag and Drop functionality to a QListWidget. The first milestone was reached with the following code.

//draglist.h
#include <QListWidget>

class SourceList : public QListWidget
{
public:
    SourceList(QWidget * parent = 0);
protected:
    void mousePressEvent(QMouseEvent *event);
};
//draglist.cpp
#include "draglists.h"
#include <QMouseEvent>
#include <QDebug>
#include <QMimeData>
#include <QDrag>

SourceList::SourceList(QWidget * parent)
    :QListWidget(parent)
{
}

void SourceList::mousePressEvent(QMouseEvent *event)
{
    //Data from the selected QListWidgetItem
    QString itemData = currentItem()->data(Qt::DisplayRole).toString();

    QMimeData *mimeData = new QMimeData;
    mimeData->setText(itemData);

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

It enabled the drag functionality for the list items, but they can't be clicked any more. How to retain the functionality in which one left click selects the item in the list (this is the behaviour if mousePressEvent() isn't overridden) ?

Possible solution

Check the source code for the original QAbstractItemView::mousePressEvent(QMouseEvent *event) and recopy the needed code int the SourceList::mousePressEvent(QMouseEvent *event) implementation. I'm looking for an alternative to that, if existent.

1

1 Answers

2
votes

To preserve the default functionality you can propagate the event up the the parent class:

void SourceList::mousePressEvent(QMouseEvent *event)
{
    // Your handling of mouse event.
    [..]
    QListWidget::mousePressEvent(event);    
}

If you need to handle the left mouse button press, you can use QMouseEvent::button() function and compare returning value with one or more Qt::MouseButton values. For example:

if (event->button() & Qt::LeftButton) {
    // Handle the left mouse button click.
}