I am trying to create a class with drag and drop. I want it to be used as a base class for future derived classes. I want derived classes to specify MIME data for Drag and Drop. I made a function that returns MIME data as a pointer, I am not sure if it is safe to do so. Is it possible that it will cause memory leak or other problems? It works now and doesn't show any warnings. I am new to Qt and don't have much experience with pointers in C , so sorry if it is a stupid question.
QMimeData* BasicGraphicsObject::setObjectMimeData()
{
QMimeData *mime = new QMimeData;
mime->setImageData(itemToImage());
mime->setText("BasicItem");
return mime;
}
Drag implementation function:
void BasicGraphicsObject::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
// This prevents mouse jitter noise, drag starts only if distance is sufficient
if (QLineF(event->screenPos(), event->buttonDownScreenPos(Qt::LeftButton))
.length() < QApplication::startDragDistance()) {
return;
}
//initialising drag event
QDrag *drag = new QDrag(event->widget());
//setting mime data with setObjectMimeData function
drag->setMimeData(setObjectMimeData());
//setting cursor as an image of the item being dragged
drag->setPixmap(itemToImage().scaled(boundingRect().size().toSize()));
drag->setHotSpot(QPoint(15,20));
drag->exec();
setCursor(Qt::OpenHandCursor);
}
CodePudding user response:
The man page for QDrag::setMimeData() says that “ownership of the QMimeData object is transferred to the QDrag object”, which is another way of saying that the QDrag object will delete the QMimeData object when it is done with it. Therefore you should not experience any memory leak of the QMimeData object (unless you somehow never call setMimeData() with it)