Catching media keys on Apple keyboard [A1234]



  • Within QT, how do I catch the 'special' buttons on an Apple keyboard (on OS X) -- the ones that play/pause a song, skip to the next/previous song [F7,F8,F9 on my particular keyboard, which is the A1234 model]?
    I did define keyPressEvent() in my subclass of QMainWindow, but pressing these function keys don't generate a keypress event.


  • Lifetime Qt Champion

    Hi,

    You can get them by implementing a QAbstractNativeEventFilter. You'll have to analyze the NSEvent object you'll get to catch the ones involving these special key.

    Hope it helps



  • Got that going.
    Trick is now to somehow get the definition on an NSEvent into Qt. There is an NSEvent.h available, but that is in Objective C.

    Thanks for the hint anyway


  • Lifetime Qt Champion

    You have to write a bit of Objective-C++, i.e. mix C++ and Objective-C.

    Basic sample:

    myapplication.pro

    TEMPLATE = app
    TARGET = myapplication
    INCLUDEPATH += .
    QT += widgets
    
    OBJECTIVE_SOURCES += main.mm
    LIBS += -framework AppKit
    

    main.mm

    #include <QApplication>
    #include <QWidget>
    #include <QAbstractNativeEventFilter>
    #include <QtDebug>
    
    #import <AppKit/AppKit.h>
    
    class CocoaNativeEventFilter : public QAbstractNativeEventFilter
    {
    public:
        bool nativeEventFilter(const QByteArray &eventType, void *message, long *) Q_DECL_OVERRIDE
        {
            if (eventType == "mac_generic_NSEvent") {
                NSEvent *event = static_cast<NSEvent *>(message);
                NSLog(@"Got event: %@", event);
            }
            return false;
        }
    };
    
    int main(int argc, char* argv[])
    {
        QApplication app(argc, argv);
        CocoaNativeEventFilter filter;
        app.installNativeEventFilter(&filter);
        QWidget w;
        w.show();
        return app.exec();
    }
    

    There's a pending update to the documentation that will provide an example.



  • Mixing Objective-C with C++ is pretty cool -- did not know that that was possible.
    Now, on to adding a whole lot of #ifdef statements so that compiling this in Linux still works.

    Thanks again for the help!


  • Lifetime Qt Champion

    There's no need for that much ifdefs.

    Keep your event filters in separated files. You can then use scopes in your .pro file to compile only the version you need for the current platform your building on.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.