Posted By

shadevampire on 09/05/11


Tagged

file files directory and drop drag directories Qt


Versions (?)

Qt drag and drop files or directories


 / Published in: C++
 

You have to implement 2 protected virtual methods in your widget you want to accept file or directory drops: - void dragEnterEvent(QDragEnterEvent *event) - void dropEvent(QDropEvent *event)

And also you have to call setAcceptDrops(true); on this widget before it could accept drops.

  1. void MainWindow::dragEnterEvent(QDragEnterEvent *event)
  2. {
  3. if(event->mimeData()->hasUrls()) {
  4. event->acceptProposedAction();
  5. }
  6. }
  7.  
  8. void MainWindow::dropEvent(QDropEvent *event)
  9. {
  10. QList<QUrl> droppedUrls = event->mimeData()->urls();
  11. int droppedUrlCnt = droppedUrls.size();
  12. for(int i = 0; i < droppedUrlCnt; i++) {
  13. QString localPath = droppedUrls[i].toLocalFile();
  14. QFileInfo fileInfo(localPath);
  15. if(fileInfo.isFile()) {
  16. // file
  17. QMessageBox::information(this, tr("Dropped file"), fileInfo.absoluteFilePath());
  18. }
  19. else if(fileInfo.isDir()) {
  20. // directory
  21. QMessageBox::information(this, tr("Dropped directory"), fileInfo.absoluteFilePath());
  22. }
  23. else {
  24. // none
  25. QMessageBox::information(this, tr("Dropped, but unknown"), tr("Unknown: %1").arg(fileInfo.absoluteFilePath()));
  26. }
  27. }
  28.  
  29. event->acceptProposedAction();
  30. }

Report this snippet  

You need to login to post a comment.