How to obtain source dragged of drag & drop operation in QTreeWidget

1.6k views Asked by At

(Sorry for my english)

I am currently trying to make a drag & drop in a QTreeWidget. So I put the corresponding settings and the method dropEvent :

class TreeWidget : public QTreeWidget
{
protected:

  virtual void dropEvent(QDropEvent *event) override
  {
    QModelIndex index = indexAt(event->pos());
    if (!index.isValid()) {  // just in case
      event->setDropAction(Qt::IgnoreAction);
      return;
    }

    QTreeWidgetItem* item = itemFromIndex(index);
    qDebug() << "drop on item" << item->text(0);

    QTreeWidget::dropEvent(event);
  }
};

int main()
{
  TreeWidget *listWidget = new TreeWidget;
  listWidget->setSelectionMode(QAbstractItemView::SingleSelection);
  listWidget->setDragEnabled(true);
  listWidget->viewport()->setAcceptDrops(true);
  listWidget->setDropIndicatorShown(true);
  listWidget->setDragDropMode(QAbstractItemView::InternalMove);
}

But in my case, I would like to move only parent items. In the code, I get the destination item, but how get dragged item ?

Have I to overload a drag method ? Launch the drag myself from mousePressEvent ? What is the best way to do ?

Thanks !

1

There are 1 answers

3
m7913d On

You can obtain the dragged item with QDropEvent::source:

If the source of the drag operation is a widget in this application, this function returns that source; otherwise it returns 0.

Afterwards you can try to convert it to a more specific Qt class, i.e. QTreeWidget, using qobject_cast. If the object wasn't derived from the requested class, 0 will be returned:

Returns the given object cast to type T if the object is of type T (or of a subclass); otherwise returns 0. If object is 0 then it will also return 0.