Search code examples
qtqtreewidgetqtreewidgetitemqmouseevent

Multiple file insert in QTreewidget using Drag and Drop events


I am working in Qt4.7 on MAC OSx. I want to insert files in QTreewidget using the Drag and Drop events. I want to add multiple files at a time. I am using this:

void MainWindow::dragEnterEvent(QDragEnterEvent * e)
{
    if(e->mimeData()->hasUrls())
    {
        e->acceptProposedAction();
    }

}
void MainWindow::dropEvent(QDropEvent * e)
{
    QTreeWidgetItem *Items = new QTreeWidgetItem(ui->treeWidget);
    foreach(const QUrl &url,e->mimeData()->urls())
    {
        const QString &filename = url.toLocalFile();
        qDebug() << "Dropped file:" << filename;
        Items->setText(0,filename);
    }
}

Using this, I am able to insert only one file at a time. Is there anyone who can help me out in this issue ? Your help will really appreciate.

Thanks, Ashish.


Solution

  • The problem is that you create only one tree view item. However you need one per each Url you passed with the mime data:

    void MainWindow::dropEvent(QDropEvent *e)
    {
        foreach(const QUrl &url, e->mimeData()->urls()) {
            QString filename = url.toLocalFile();
            qDebug() << "Dropped file:" << filename;
            QTreeWidgetItem *item = new QTreeWidgetItem(ui->treeWidget);
            item->setText(0, filename);
        }
    }