简体   繁体   中英

Drag and drop onto a QStandardItemModel in a QTreeView not working

I have a QTreeView with a QStandardItemModel attached to it. I am trying to enabled drag and drop from external sources. I've done everything mentioned in the documentation for drag and drop and drag and drop with item views, but things aren't working right. When I try to drag a file onto the tree view, the icon always has an X on it saying that drop isn't available. (I use OS X, I don't know what the icon would look like it windows). I want to be able to drop on certain items, but until I get the basics down, I can't code that functionality.

Here is my subclassed tree view source code:

MyTreeView::MyTreeView(QWidget *parent) :
    QTreeView(parent)
{
    setContextMenuPolicy(Qt::CustomContextMenu);
    setAcceptDrops(true);
    setDropIndicatorShown(true);
}

void MyTreeView::dragEnterEvent(QDragEnterEvent *event)
{
    event->acceptProposedAction();
}

void MyTreeView::dropEvent(QDropEvent *event)
{
    qDebug("I am here");
    event->acceptProposedAction();
}

and here is the source for the subclassed standard item model:

MyStandardItemModel::MyStandardItemModel(QObject *parent) :
    QStandardItemModel(parent)
{
}

Qt::DropActions MyStandardItemModel::supportedDropActions() const
{
    return Qt::CopyAction;
}

Qt::ItemFlags MyStandardItemModel::flags(const QModelIndex &index) const
{
    Qt::ItemFlags defaultFlags = QStandardItemModel::flags(index);

    if (index.isValid())
        return Qt::ItemIsDropEnabled | defaultFlags;
    else
        return defaultFlags;
}

bool MyStandardItemModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent)
{
    qDebug("I am in the model");
}

As I said, the icon is telling me that drop is not available, but if I drop it anyhow, the text "I am here" from the tree view gets printed. But the text "I am in the model" from the model view never gets printed. I'm not sure what I need to do to get the model to recognize that drops are available and change the icon, or to get the dropMimeData function to call. Any help is appreciated, because I've read the documentation over and over and I'm clearly missing something.

I think this is because you also need to reimplement the dragMoveEvent(QDragMoveEvent*) method. Otherwise, each item, independently, will declare they can't accept the drop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM