QList Drag and Drop Example
Jump to navigation
Jump to search
This article may require cleanup to meet the Qt Wiki's quality standards. Reason: Auto-imported from ExpressionEngine. Please improve this article if you can. Remove the {{cleanup}} tag and add this page to Updated pages list after it's clean. |
Example of the simple moving items using drag & drop betweeen two or more QListViews.
listbox.h:
#ifndef LISTBOX_H
#define LISTBOX_H
#include <QtGui>
class ListBox : public QListWidget
{
Q_OBJECT
public:
ListBox(QWidget *parent);
protected:
void dragMoveEvent(QDragMoveEvent *e);
void dropEvent(QDropEvent *event);
void startDrag(Qt::DropActions supportedActions);
void dragEnterEvent(QDragEnterEvent *event);
Qt::DropAction supportedDropActions();
signals:
void itemDroped();
};
#endif // LISTBOX_H
listbox.cpp:
#include "listbox.h"
void ListBox::dragMoveEvent(QDragMoveEvent *e)
{
if (e->mimeData()->hasFormat("application/x-item") && e->source() != this) {
e->setDropAction(Qt::MoveAction);
e->accept();
} else
e->ignore();
}
ListBox::ListBox(QWidget *parent) : QListWidget(parent)
{
this->setViewMode(QListView::IconMode);
this->setIconSize(QSize(55, 55));
this->setSelectionMode(QAbstractItemView::SingleSelection);
this->setDragEnabled(true);
this->setDefaultDropAction(Qt::MoveAction);
this->setAcceptDrops(true);
this->setDropIndicatorShown(true);
}
void ListBox::dropEvent(QDropEvent *event)
{
if (event->mimeData()->hasFormat("application/x-item")) {
event->accept();
event->setDropAction(Qt::MoveAction);
QListWidgetItem *item = new QListWidgetItem;
QString name = event->mimeData()->data("application/x-item");
item->setText(name);
item->setIcon(QIcon(":/images/iString")); //set path to image
addItem(item);
}
else
event->ignore();
}
void ListBox::startDrag(Qt::DropActions supportedActions)
{
QListWidgetItem *item = currentItem();
QMimeData *mimeData = new QMimeData;
QByteArray ba;
ba = item->text().toLatin1().data();
mimeData->setData("application/x-item", ba);
QDrag *drag = new QDrag(this);
drag->setMimeData(mimeData);
if (drag->exec(Qt::MoveAction) == Qt::MoveAction) {
delete takeItem(row(item));
emit itemDroped();
}
}
void ListBox::dragEnterEvent(QDragEnterEvent *event)
{
if (event->mimeData()->hasFormat("application/x-item"))
event->accept();
else
event->ignore();
}
Qt::DropAction ListBox::supportedDropActions()
{
return Qt::MoveAction;
}