2

I have a custom QTreeWidget class with the dropEvent() method overridden. Here is the method:

void QCustomTreeWidget::dropEvent(QDropEvent * event)
{
    QModelIndex droppedIndex = indexAt(event->pos());

    if (!droppedIndex.isValid())
        return;

    // other logic

    QTreeWidget::dropEvent(event);
}

How can I determine if the item will be inserted above, inside or below the item on which it is dropped?

IAmInPLS
  • 4,051
  • 4
  • 24
  • 57
Mihai
  • 389
  • 1
  • 4
  • 16

1 Answers1

6

You need to use the DropIndicatorPosition. With a switch statement, you can easily achieve what you want.

bool bAbove = false; // boolean for the case when you are above an item

QModelIndex dropIndex = indexAt(event->pos());
DropIndicatorPosition dropIndicator = dropIndicatorPosition();

if (!dropIndex.parent().isValid() && dropIndex.row() != -1)
{
    switch (dropIndicator)
    {
    case QAbstractItemView::AboveItem:
        // manage a boolean for the case when you are above an item
        bAbove = true;
        break;
    case QAbstractItemView::BelowItem:
        // something when being below an item
        break;
    case QAbstractItemView::OnItem:
        // you're on an item, maybe add the current one as a child
        break;
    case QAbstractItemView::OnViewport:
        // you are not on your tree
        break;
    }

    if(bAbove) // you are above an item
    {
        // manage this case
    }
}
IAmInPLS
  • 4,051
  • 4
  • 24
  • 57
  • 1
    Most answers to this questions just tell to use the `itemAt(event->pos())`, but actually this is the right way to do it, excellent! – Andy Reimann Jul 26 '17 at 22:28