6th July 2015 | By:

How to handle a file open event with QT in Mac OSX

By assigning the file type to a specific file we can determine what kind of information and data we expect to find inside that particular file. There are a lot of applications that handle multiple file types, so we want to use specific one that can be reserved only for the given application. By double clicking on the file the default app will be launched and the file loaded into it.
It’s fairly easy to bind any file type to our custom application. To achieve this on Mac OSX we first need to modify the Info.plist file located inside the app Contents folder. To bind a particular file type the `CFBundleDocumentTypes` element should be created. We will assume that our custom file type has the `.ourtype` extension:
[code language=”xml”]
<false />
Explanation of keys:

CFBundleTypeName String The abstract name of the document type (also called its kind string)
CFBundleTypeIconFile String The name of the icon file for displaying documents of this type
CFBundleTypeOSTypes Array An array of four-character file types for documents belonging to this document type
CFBundleTypeExtensions Array An array of filename extensions for documents belonging to this document type
CFBundleTypeMIMETypes Array An array of MIME types for documents belonging to this document type
CFBundleTypeRole String The role the application claims with respect to documents of this type; see Application Roles
LSTypeIsPackage Boolean Specifies whether the document is distributed as a bundle

Now when we double click on a file with extension `.ourtype`, the application will be launched. The next step is to handle the file open event inside the application. This event is triggered only on Mac OSX, on Windows and Linux file name it is passed inside the `**argv` list. To catch the clicked file path, the `QApplication` needs to be inherited and the `event` function overloaded:
[code language=”cpp”]
#include <QApplication>
#include <QFileOpenEvent>
#include <QEvent>
class MyApplication : public QApplication{
MyApplication(int &amp;argc, char **argv) : QApplication(argc, argv){}
bool event(QEvent *){ // the open file event handler
switch (event->type()) {
// catch only FileOpen event
case QEvent::FileOpen:
// cast file name from passed event
const QString file_name = static_cast(event)->file();
// handle file open here
return true;
return QApplication::event(event);
Now after double clicking on the file, the file name with the full path can be caught by the application. Enjoy!

Tags: , , , ,

1 Comment

  1. pitch
    29th January 2016 @ 6:54

    Not Working on me 🙁


Leave a reply

Your email address will not be published. Not now, not ever. Required fields are marked *


You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>