Important: Please read the Qt Code of Conduct -

How to get the pointer or name of a widget when dragging an item

  • First, please watch the video to get the issue. Thank you.
    link text

    My Problem is the item is gone after dragging in a wrong widget.
    I've tried to use "enterEvent" or "dragEnterEvent" to get the pointer of the left widget in the video.
    But it can't, because it can't trigger the enterEvent or dragEnterEvent of the left widget when I'm dragging an item. Therefore, I can't stop the removing mechanism of the QListWidget.

    My current solution is to use "isQListWidget (bool)" as a condition to trigger the removing mechanism, but no way can make isQListWidget works.

    My code is:

    void listWidgetMaya::startDrag(Qt::DropActions supportedActions)
        //Declare a QListWidgetItem and get the currentItem
        QList<QListWidgetItem*> items = this->selectedItems();
        foreach(QListWidgetItem *item, items){
            QMimeData* mimeData = new QMimeData;
            QByteArray ba;
            ba = item->text().toLatin1().data();
            mimeData->setData("application/x-item", ba);
            QDrag* drag = new QDrag(this);
            //Execute the moving
            //Removing Mechanism of QListWidget
            if( isQListWidget == true){
                delete takeItem(row(item));

  • Lifetime Qt Champion


    Have a look at

    it checks if the drop was accepted. and then first delete the item.

    you code will just do , regardless if it was accepted or not.

    so you need like

    if (drag->exec(Qt::MoveAction) == Qt::MoveAction)
            delete takeItem(row(item));

  • @mrjj Thank you. The code works perfectly.

Log in to reply