Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How to drag and drop QStandardItems containing file paths in a Treeview to a file on the desktop or another application?



  • I have a treeview which is modeling a file tree. Each item in the TreeView is a QstandardItem that holds a file path. I would like to be able to get the file it referes to and drag the item into another application. The files are all video files so I would like to add the ability to drag and drop into VLC, Adobe Premier etc.

    There are a lot of posts with similar questions but the answers are kind of all over the place so any resources will be of great help.

    Thanks!



  • Subclass your QStandardItemModel with something like this:

    class FileItemModel : public QStandardItemModel{
        Q_OBJECT
        Q_DISABLE_COPY(FileItemModel)
    public:
        using QStandardItemModel::QStandardItemModel;
        QMimeData *mimeData(const QModelIndexList &indexes) const override{
            QMimeData *result  = QStandardItemModel::mimeData(indexes);
            if(result){
                QList<QUrl> urls;
                for (auto&& idx : indexes){
                    urls << QUrl::fromLocalFile(idx.data()); /*this assumes the full path to the file is stored in DisplayRole, change according to your needs*/
                }
                result->setUrls(urls);
            }
            return result; 
        }
        QStringList mimeTypes() const override{
            return QStandardItemModel::mimeTypes() << QStringLiteral("text/uri-list");
        }
    };
    

Log in to reply