Qt Drag&删除:添加对将文件拖动到应用程序主窗口的支持

时间:2013-02-15 13:00:51

标签: c++ qt drag-and-drop

许多应用程序允许用户将一个或多个文件拖到应用程序的主窗口。

如何在我自己的Qt应用程序中添加对此功能的支持?

3 个答案:

答案 0 :(得分:39)

dragEnterEvent()课程中重载dropEvent()MainWindow,并在构造函数中调用setAcceptDrops()

MainWindow::MainWindow(QWidget *parent)
{
    ..........
    setAcceptDrops(true);
}

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

void MainWindow::dropEvent(QDropEvent *e)
{
    foreach (const QUrl &url, e->mimeData()->urls()) {
        QString fileName = url.toLocalFile();
        qDebug() << "Dropped file:" << fileName;
    }
}

答案 1 :(得分:6)

首先,检查Qt Reference Documentation: Drag and Drop的基础知识,然后查看Drag and Drop of files on QMainWindows的技术内容。后者提供了一个完整的例子。

Qt也有一堆Drag and Drop examples,您可能对Drop Site感兴趣。

答案 2 :(得分:3)

我在此链接中获得了整个代码:Drag and Drop files into your application。您可以从此页面下载 .zip

代码对我来说非常完美,我应该做的唯一一件事就是将代码包含在我的 mainwindow.h 中:

#include <QMimeData>

这就是全部,我希望它可以帮到你。

相关问题