28

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

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

4

2 回答 2

46

重载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;
    }
}
于 2013-02-15T13:05:17.570 回答
7

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

Qt 还有一堆拖放示例,您可能对Drop Site感兴趣。

于 2013-02-15T13:09:52.590 回答