April 30, 2009
Handle file drop in QT
File drop is an easy-to-use feature for users, as users can directly drag-and-drop a file from file browser onto your application. People may think it is difficult to implement. But actually, it is rather easy. Here is a fast way to start.
The main idea is to handle these two events, QDropEvent and QDragEnterEvent. The following shows how to handle them in your app.
First, add the following code to the class declaration in a header file,
protected:
void dropEvent(QDropEvent *event);
void dragEnterEvent(QDragEnterEvent *event);
Then add the implementation to the cpp file,
void CLASS::dragEnterEvent(QDragEnterEvent *event)
{
if (event && event->mimeData()) {
const QMimeData* md = event->mimeData();
if (md->hasUrls())
event->acceptProposedAction();
}
}
and
void CLASS::dropEvent(QDropEvent *event)
{
const QMimeData *data = event->mimeData();
if(data->hasUrls())
foreach(QUrl url, data->urls()) {
QFileInfo info(url.toLocalFile());
if(info.exists() && info.isFile())
///// do something with url.tolocalFile()
}
}
One more thing, add the following code in the constructor of the class to enable the widget to accept the events.
setAcceptDrops(true);
That’s all!
Tags: QT

Comments(1)