PDA

View Full Version : How to make an icon widget draggable



curiouswalker
18th November 2010, 06:55
Hello everybody,

I have an icon widget, and I want to make this widget be draggable which means when user press the mouse on this widget and drag it, this icon shall be moved under the mouse and until the mouse was release.

I was trying to use the drag and drop mechanism to implement this feature, only to find that it can't give me what I need. Please see my code in the following section,

Code:

void DragWidget::dragMoveEvent(QDragMoveEvent *event)
{
if (event->mimeData()->hasFormat("application/x-dnditemdata")) {

QByteArray itemData = event->mimeData()->data("application/x-dnditemdata");
QDataStream dataStream(&itemData, QIODevice::ReadOnly);

QPixmap pixmap;
QPoint offset;
dataStream >> pixmap >> offset;

//QLabel *newIcon = new QLabel(this);
//newIcon->setPixmap(pixmap);
//repaint();
//newIcon->show();
//newIcon->setAttribute(Qt::WA_DeleteOnClose);

if (event->source() == this) {
event->setDropAction(Qt::MoveAction);
event->accept();
} else {
event->acceptProposedAction();
}

move(event->pos() - offset);
}
else {
event->ignore();
}
}

void DragWidget::dropEvent(QDropEvent *event)
{
if (event->mimeData()->hasFormat("application/x-dnditemdata")) {
QByteArray itemData = event->mimeData()->data("application/x-dnditemdata");
QDataStream dataStream(&itemData, QIODevice::ReadOnly);

QPixmap pixmap;
QPoint offset;
dataStream >> pixmap >> offset;

QLabel *newIcon = new QLabel(this);
newIcon->setPixmap(pixmap);
newIcon->move(event->pos() - offset);
newIcon->show();
newIcon->setAttribute(Qt::WA_DeleteOnClose);

if (event->source() == this) {
event->setDropAction(Qt::MoveAction);
event->accept();
} else {
event->acceptProposedAction();
}
} else {
event->ignore();
}
}


Can someone help me out?

curiouswalker
19th November 2010, 01:23
The following method may work, I will have a try.


QGraphicsItem::ItemIsMovable

0x1 The item supports interactive movement using the mouse. By clicking on the item and then dragging, the item will move together with the mouse cursor. If the item has children, all children are also moved. If the item is part of a selection, all selected items are also moved. This feature is provided as a convenience through the base implementation of QGraphicsItem's mouse event handlers.