While working on Simple Sysexxer, I wished to add drag’n'drop support to open files. Thanks to QT4 it was quite simple. The following code has basically been derived from the book C++ GUI Programming with Qt4 and slightly modified to fit into the existing code.
In the constructor of the widget to accept drops (e.g. your application’s main window), set setAcceptDrops( true );.
Then reimplement the following two functions:
void dragEnterEvent( QDragEnterEvent* );
void dropEvent( QDropEvent* );
The first one determines wether your application wants to accept certain datatypes or not. In my case, I simply want to accept lists of URIs:
void MainWindow::dragEnterEvent( QDragEnterEvent* DragEvent )
{
if ( DragEvent->mimeData()->hasFormat( "text/uri-list" ) )
DragEvent->acceptProposedAction();
}
My application can only handle one file at a time. An URI list which is empty or contains more than one entry is rejected:
void MainWindow::dropEvent( QDropEvent* DropEvent )
{
QList
if ( urls.isEmpty() )
return;
if ( urls.size() > 1 )
{
emit errorMessage( tr( "This application can only open one file at a time." ), tr( "Please drop one file only." ) );
return;
}
The first (and hopefully only) item in the list is checked wether it is a local filesystem path:
QString filePath = urls.first().toLocalFile();
if ( filePath.isEmpty() )
return;
If the user accepts that the currently loaded data will be discarded, the given filename is opened (the existence and readibility of the file is checked in loadFile() ):
if ( confirmDataLoss() == false )
return;
discardData();
loadFile( filePath );
}