Frage

I'm using Qt 4.2.

I've a QMainWindow with a QListView inside which uses a QStandardItemModel for showing some items that I get from .desktop files.

Now I'm trying to implement a drop action over the app so for ex: I can run firefox when a .html file is droped over the firefox item.

So this is what I've done:

-for the listView:

 viewport()->setAcceptDrops(true);
 setAcceptDrops(true);
 setDragEnabled(true);
 setDropIndicatorShown(true);
 setDragDropMode(QListView::DragDrop);

-for the standardItemModel:

Qt::DropActions supportedDropActions() const {
    return Qt::CopyAction | Qt::MoveAction;
}
Qt::ItemFlags flags(const QModelIndex &index) const {
    return Qt::ItemIsSelectable | Qt::ItemIsDragEnabled |
           Qt::ItemIsDropEnabled | Qt::ItemIsEnabled;
}
QStringList mimeTypes() const {
    QStringList types;
    types<<"text/uri-list";
    return types;
}
bool dropMimeData(const QMimeData *data, Qt::DropAction action,
                  int row, int column, const QModelIndex &parent) {
    qDebug() << "dropMimeData";
}

After that, I never get the dropMimeData debug message when I drop some file over the app.

War es hilfreich?

Lösung

You also need to reimplement dragEnterEvent() and dropEvent() - they are virtual functions in QListView.

From the documentation:

Dropping

To be able to receive media dropped on a widget, call setAcceptDrops(true) for the widget, and reimplement the dragEnterEvent() and dropEvent() event handler functions.

For example, the following code enables drop events in the constructor of a QWidget subclass, making it possible to usefully implement drop event handlers:

 void Window::dragEnterEvent(QDragEnterEvent *event)
 {
     if (event->mimeData()->hasFormat("text/plain"))
         event->acceptProposedAction();
 }


 void Window::dropEvent(QDropEvent *event)
 {
     textBrowser->setPlainText(event->mimeData()->text());
     mimeTypeCombo->clear();
     mimeTypeCombo->addItems(event->mimeData()->formats());

     event->acceptProposedAction();
 }
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top