1

I have very simple code, that displays file structure:

class MainWindow : public QMainWindow
{
    Q_OBJECT
private:
    Ui::MainWindow *ui;
    QFileSystemModel model;
    QTreeView treeView;
};

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    model.setRootPath(QDir::rootPath());
    ui->treeView->setModel(&model);
    ui->treeView>setSelectionMode(QAbstractItemView::SingleSelection);
    ui->treeView->setDragEnabled(true);
    ui->treeView->viewport()->setAcceptDrops(true);
    ui->treeView->setDropIndicatorShown(true);
    ui->treeView->setDragDropMode(QAbstractItemView::InternalMove);
    ui->treeView->setAcceptDrops(true);

    ui->tableView->setModel(&model);
}

I can select file and drag & drop it directly to folder or on desktop, but when I try to do something internally (move or copy, doesn't matter) it shows this example - even cursor shows that I can't drop It seems to me, that I've tried all options, Did I forget something to write or set other option ?

edff
  • 11
  • 1

1 Answers1

5

I have implemented QTreeView-based UI widget with QFileSystemModel as data source and enabled drag and drop for the view but still cannot see the cursor showing it is ready for the "drop" action. What did I miss?

Answering you from experience after peeking at similar code. In order to resolve the item accepting the drop a bit more work needed on model's side:

// MyFileSysModel is a child from model class used in your example.
// Mind that specific application drag and drop logic may differ.
// I in fact modified that from QSortFilterProxyModel-type of class
// but that should be similar.
Qt::ItemFlags MyFileSysModel::flags(const QModelIndex &index) const
{
    Qt::ItemFlags defaultFlags = QFileSystemModel::flags(index);

    if (!index.isValid())
        return defaultFlags;

    const QFileInfo& fileInfo = this->fileInfo(index);

    // The target
    if (fileInfo.isDir())
    {
        // allowed drop
        return Qt::ItemIsDropEnabled | defaultFlags;
    }
    // The source: should be directory (in that case)
    else if (fileInfo.isFile())
    {
        // allowed drag
        return Qt::ItemIsDragEnabled | defaultFlags;
    }

    return defaultFlags;
}

... and of course we need to use the derived model class now:

class MainWindow : public QMainWindow
{
    Q_OBJECT
private:
    Ui::MainWindow *ui;
    MyFileSysModel model; // has virtual function member "flags"
    QTreeView treeView;
};
Alexander V
  • 8,351
  • 4
  • 38
  • 47