Dropping things on app icons with Qt

I’ve spent the last year or so attempting to improve the users experience of the application I spend my (working) life developing and maintaining. This has involved many new and exciting changes, but the biggest one is the ability to just drop data and files onto the applications icon and windows rather than using dialogs to locate and import things. To do this with a Mac OSX application developed with Qt requires two steps:

  1. Subclass QApplication and reimplement the event() method
  2. Update the applications Info.plist to register associated file types

So, step 1 is relatively simple:

application.h

#ifndef APPLICATION_H
#define APPLICATION_H

#include <QApplication>

class Application : public QApplication
{
    Q_OBJECT
public:
    Application(int &argc, char** argv);
    ~Application();
protected:
    bool event(QEvent *);
private:
    void loadFile(const QString &fileName);

};

#endif // APPLICATION_H

application.cpp

#include "application.h"

#include <QFileOpenEvent>
#include <QDebug>

Application::Application(int &argc, char **argv) : QApplication(argc,argv){}
Application::~Application(){}

bool Application::event(QEvent *event){
    switch(event->type()){
    case QEvent::FileOpen:
        loadFile(static_cast<QFileOpenEvent *>(event)->file());
        return true;
    default:
        return QApplication::event(event);
    }
}

void Application::loadFile(const QString &fileName){
    qDebug() << "File Name:" << fileName;
}

You can then use this in place of QApplication, obviously after doing something more useful in the loadFile() method.

Step 2 simply involves inserting the following somewhere in your Info.plist file:

...
    <key>CFBundleDocumentTypes</key>
    <array>
        <dict>
            <key>CFBundleTypeExtensions</key>
            <array>
                <string>txt</string>
            </array>
            <key>CFBundleTypeIconFile</key>
            <string>application.icns</string>
            <key>CFBundleTypeMIMETypes</key>
            <array>
                <string>text/plain</string>
            </array>
            <key>CFBundleTypeName</key>
            <string>Text</string>
            <key>CFBundleTypeRole</key>
            <string>Viewer</string>
            <key>LSIsAppleDefaultForType</key>
            <false/>
        </dict>
    </array>
...

And you’re done! To automatically update the Info.plist file after the application has built rather than (forgetting to) update by hand, see my previous post about running scripts from Qt project files.

Share:
Facebook
Twitter
Google+
http://www.gulon.co.uk/2015/10/22/dropping-things-on-app-icons-with-qt/
RSS
Follow by Email
SHARE

Leave a Reply

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