How to Add Drag & Drop Capability in Your Qt Application

Allowing the users of your Qt application (regardless of whatever its purpose is) to use Drag & Drop is a very important aspect of writing easy to use apps and user interfaces. In this post I have described how to add Drag & Drop functionality in your Qt programs with just a few simple steps.

First of all you need to override two important functions in your MainWindow or any other class that you want Drag & Drop to be enabled. I assume it’s MainWindow so add the following lines to it in the header file:

protected:
void dragEnterEvent(QDragEnterEvent *e);
void dropEvent(QDropEvent *e);

Next you have to write codes for these two override functions. Add the code below to your CPP file to enable Drag & Drop if the user is trying to Drag files over to your application. Note that it is very important to check if the dragged object or objects are usable by your program:

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


Finally you can get the list of files that are dropped into your program by adding the code below to your CPP file. Notice that you can filter out the files that you don’t want by setting the values in accepted_types variable:

void MainWindow::dropEvent(QDropEvent* e)
{
	QStringList accepted_types;
	accepted_types << "jpeg" << "jpg" << "png";
	foreach(const QUrl & url, e->mimeData()->urls())
	{
		QString fname = url.toLocalFile();
		QFileInfo info(fname);
		if (info.exists())
		{
			if (accepted_types.contains(info.suffix().trimmed(), Qt::CaseInsensitive))
				// do whatever you need to do with fname variable
		}
	}
}


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.