1

(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 !

m7913d
  • 10,244
  • 7
  • 28
  • 56
Maluna34
  • 245
  • 1
  • 16

1 Answers1

1

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.

m7913d
  • 10,244
  • 7
  • 28
  • 56
  • 1
    Unfortunately, QTreeWidget item is not a derived from QObject. We advise me to use QTreeWidget::currentItem() to get the moved element. It does not use the QDropEvent parameter but it seems to work. – Maluna34 Jun 28 '17 at 07:21
  • `QObject` source is a `QTreeWidget`. So you can request `currentItem` from the source `QTreeWidget`. – m7913d Jun 28 '17 at 07:41
  • 1
    @Maluna34 You should check the source any way. Otherwise you could accept drop events from any source, interpreting it as a moved item of your tree! – king_nak Jun 28 '17 at 07:51