How can I implement drag and drop in my QListView in Qt 3?
Answer:
You need to subclass QListView and reimplement dragObject() to
create a drag object. If you want your listview items to be able to
accept drops then you need to subclass QListViewItem as well and
reimplement acceptDrop() and dropped(). See the example below for a
demonstration.
#include <qapplication.h>
#include <qdragobject.h>
#include <qlistview.h>
class DragDropListViewItem : public QListViewItem
{
public:
DragDropListViewItem(QListView *parent) : QListViewItem(parent)
{
setDragEnabled(true);
setDropEnabled(true);
}
bool acceptDrop(const QMimeSource *mime) const
{
// This is called to see if this item will accept the drop
// If we can decode this text then we will accept the drop
// otherwise we will not
return QTextDrag::canDecode(mime);
}
protected:
void dropped(QDropEvent *e)
{
// This is called when the drop occurs on this item
// Decodes the drop event and sets the text on the 1st column
// to prove it worked :)
QString str;
QTextDrag::decode(e, str);
setText(1, str);
}
};
class DragDropListView : public QListView
{
public:
DragDropListView(QWidget *parent = 0, const char *name = 0) :
QListView(parent, name)
{
// setAcceptDrops() must also be called
viewport()->setAcceptDrops(true);
setAcceptDrops(true);
addColumn("Text");
addColumn("Dragged Text");
DragDropListViewItem *item = new DragDropListViewItem(this);
item->setText(0, "Item One");
item = new DragDropListViewItem(this);
item->setText(0, "Item Two");
item = new DragDropListViewItem(this);
item->setText(0, "Item Three");
}
protected:
QDragObject *dragObject()
{
// Return any drag object here really, it will be decoded yourself
// anyway. In this case we are basically passing around the text
// from the first column
return new QTextDrag(selectedItem()->text(0), this);
}
};
int main(int argc, char** argv)
{
QApplication a(argc,argv);
DragDropListView l;
a.setMainWidget(&l);
l.show();
return a.exec();
}