strange behavior with object name in drag-and-drop example
-
Hello,
I am trying with this example in qt folder:https://doc.qt.io/qt-5/qtwidgets-draganddrop-draggableicons-example.html
I need to know which Icon the user is clicking on. therefore in the constructor, I added an object name for each QLabel object:
boatIcon->setObjectName("xxxx");when mousePressEvent is called, I can read the object name :
qDebug() << child->objectName() ;the problem is that objectName() is removed once I drag and drop an icon. so the second time I drag the same icon, qDebug() << child->objectName() shows nothing -- > ""
-
Hi
In
void DragWidget::dropEvent(QDropEvent *event)it gets recreated
QLabel *newIcon = new QLabel(this);
The labels are created and deleted over and over and hence after first drag, it will lose its name.
To know what was dropped, you can do the following
in void DragWidget::mousePressEvent(QMouseEvent *event) ... dataStream << pixmap << QPoint(event->pos() - child->pos()) << child->objectName(); <<<<< add data ....
and then in
dataStream >> pixmap >> offset >> OName; <<<<< take the name out again QLabel *newIcon = new QLabel(this); newIcon->setObjectName(OName); // setName again on new instance
-
The labels are created and deleted over and over
That's kind of strange, since we know
QObject
s cannot be copied...?In fact, that's really bad, because you might have attached any number of arbitrary properties/attributes, you might have subclassed and added almost anything, etc.? I don't get it....
-
@JonB
Hi
Well its by samples design
Instead of moving the same label, they flag it withboatIcon->setAttribute(Qt::WA_DeleteOnClose);
and then on a good drag
if (drag->exec(Qt::CopyAction | Qt::MoveAction, Qt::CopyAction) == Qt::MoveAction) {
child->close(); // this deletes itSo yeah this sample is not good in such case that your label is used as more than a Pixmap viewer.
I think it was chosen so as not to have to store a pointer to the QLabel and have the logic to move it between DragWidgets (parent) and
such.