简体   繁体   English

将文件拖放到Qt5应用程序外部

[英]Drag and Drop a file outside a Qt5 application

I'm trying to create a Push Button in my Qt5 application which can be dragged outside the application and when dropped, would copy a file to that location. 我正在尝试在Qt5应用程序中创建一个按钮,可以将其拖动到应用程序外部,并在拖放时将文件复制到该位置。

Take Google Chrome browser, for example. 以Google Chrome浏览器为例。 When a file is downloaded, it could be dragged from the list which appears on the bottom of the window to any other places, like a directory. 下载文件后,可以将其从窗口底部显示的列表中拖到其他任何位置,例如目录。

Is there any specialized widget to accomplish this task or do I have to write one on my own? 是否有专门的小部件来完成此任务,还是我必须自己编写一个? If so, how? 如果是这样,怎么办? I'm a capable C++ programmer but not much experienced with Qt framework. 我是一个有能力的C ++程序员,但是对Qt框架没有太多的经验。

Did you try Draggable Text Example ? 您是否尝试过“可拖动文字示例”

In the dragwidget.cpp file, if you look a the function mousePressEvent, you could see that QDrag need mimeData dragwidget.cpp文件中,如果您查看函数mousePressEvent,则可以看到QDrag需要mimeData

QDrag *drag = new QDrag(this);
drag->setMimeData(mimeData); 

Mimedata define your QDrag behaviour, like if you drag an image, file or text or anything else. Mimedata定义您的QDrag行为,就像您拖动图像,文件或文本或其他任何东西一样。

If you want to tell windows that you have file in your drag, you need to add an URL in your mimedata with something like : 如果要告诉Windows拖动文件中包含文件,则需要在mimedata中添加类似以下内容的URL:

mimeData->setUrls(QList<QUrl>() << QUrl::fromLocalFile("D:/test.txt"));

In draggabletext example, the mimedata contain text, you could see that at line [158:161]. 在draggabletext示例中,mimedata包含文本,您可以在行[158:161]看到该文本。

But if you replace the existing : 但是,如果您替换现有的:

mimeData->setText(child->text());
mimeData->setData(hotSpotMimeDataKey(),
                  QByteArray::number(hotSpot.x()) + ' ' + 
QByteArray::number(hotSpot.y()));

by 通过

mimeData->setUrls(QList<QUrl>() << QUrl::fromLocalFile("D:/test.txt"));

when you drag the text in the windows explorer, windows will accept it and copy the file where you drop it. 当您在Windows资源管理器中拖动文本时,Windows会接受该文本并将文件复制到放置该文本的位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM