Qt for macOS - Specific Issues

This page outlines the main issues regarding macOS support in Qt. macOS terminologies and specific processes are found at https://developer.apple.com/.

Aqua

Aqua is an essential part of the macOS platform. As with Cocoa and Carbon, Qt provides widgets that look like those described in the Human Interface Descriptions. Qt's widgets use HIThemes to implement the look and feel. In other words, we use Apple's own APIs for doing the rendering. More documentation about Aqua is found at the macOS Human Interface Guidelines.

The Macintosh Style Widget Gallery page contains sample images of widgets using the macOS platform theme.

Qt Attributes for macOS

The following lists a set of useful attributes that can be used to tweak applications on macOS:

macOS always double buffers the screen, therefore, the Qt::WA_PaintOnScreen attribute has no effect. Also it is impossible to paint outside of a paint event so Qt::WA_PaintOutsidePaintEvent has no effect either.

Right Mouse Clicks

The QContextMenuEvent class provides right mouse click support for macOS applications. This will map to a context menu event, for example, a menu that will display a pop-up selection. This is the most common use of right mouse clicks, and maps to a control-click with the macOS one-button mouse support.

Menu Bar

Qt detects menu bars and turns them into Mac native menu bars. Fitting this into existing Qt applications is normally automatic. However, if you have special needs, the Qt implementation currently selects a menu bar by starting at the active window (for example, QGuiApplication::focusWindow()) and applying the following tests:

  1. If the window has a QMenuBar, then it is used.
  2. If the window is modal, then its menu bar is used. If no menu bar is specified, then a default menu bar is used (as documented below).
  3. If the window has no parent, then the default menu bar is used (as documented below).

These tests are followed all the way up the parent window chain until one of the above rules is satisifed. If all else fails, a default menu bar will be created. The default menu bar on Qt is an empty menu bar. However, you can create a different default menu bar by creating a parentless QMenuBar. The first one created will be designated the default menu bar and will be used whenever a default menu bar is needed.

Using native menu bars introduces certain limitations on Qt classes. The section with the list of limitations below has more information.

Qt provides support for the Global Menu Bar with QMenuBar. macOS users expect to have a menu bar at the top of the screen and Qt honors this.

Additionally, users expect certain conventions to be respected, for example the application menu should contain About, Preferences, Quit, and so on. Qt handles these conventions, although it does not provide a means of interacting directly with the application menu.

Each QAction has a menuRole property which controls the special placement of application menu items; however by default the menuRole is TextHeuristicRole which mean the menu items will be auto-detected by their text.

Other standard menu items such as Cut, Copy, Paste and Select All are applicable both in your application and in some native dialogs such as QFileDialog. It's important that you create these menu items with the standard shortcuts so that the corresponding editing features will be enabled in the dialogs. At this time there are no MenuRole identifiers for them, but they will be auto-detected just like the application menu items when the QAction has the default TextHeuristicRole.

Special Keys

To provide the expected behavior for Qt applications on macOS, the Qt::Key_Meta, Qt::MetaModifier, and Qt::META enum values correspond to the Control keys on the standard Apple keyboard, and the Qt::Key_Control, Qt::ControlModifier, and Qt::CTRL enum values correspond to the Command keys.

Dock

Interaction with the dock is possible. The icon can be set by calling QWindow::setWindowIcon() from the main window in your application. The setWindowIcon() call can be made as often as necessary, providing an icon that can be easily updated.

Accessiblity

Many users interact with macOS with assistive devices. With Qt the aim is to make this automatic in your application so that it conforms to accepted practice on its platform. Qt uses Apple's accessibility framework to provide access to users with disabilities.

Library and Deployment Support

Qt provides support for macOS structures such as Frameworks and bundles. It is important to be aware of these structure as they directly affect the deployment of applications.

Qt provides a deploy tool, macdeployqt, to simplify the deployment process. The Qt for macOS - Deployment article covers the deployment process in more detail.

Qt Libraries as Frameworks

By default, Qt is built as a set of frameworks. Frameworks are the macOS preferred way of distributing libraries. The Apple's Framework Programming Guide site has far more information about Frameworks.

It is important to remember that Frameworks always link with release versions of libraries. If the debug version of a Qt framework is desired, use the DYLD_IMAGE_SUFFIX environment variables to ensure that the debug version is loaded:

export DYLD_IMAGE_SUFFIX=_debug

Alternatively, you can temporarily swap your debug and release versions, which is documented in Apple's "Debugging Magic" technical note.

If you don't want to use frameworks, simply configure Qt with -no-framework.

./configure -no-framework

Bundle-Based Libraries

If you want to use some dynamic libraries in the macOS application bundle (the application directory), create a subdirectory named Frameworks in the application bundle directory and place your dynamic libraries there. The application will find a dynamic library if it has the install name @executable_path/../Frameworks/libname.dylib.

If you use qmake and Makefiles, use the QMAKE_LFLAGS_SONAME setting:

QMAKE_LFLAGS_SONAME  = -Wl,-install_name,@executable_path/../Frameworks/

Alternatively, you can modify the install name using the install_name_tool(1) on the command line.

The DYLD_LIBRARY_PATH environment variable will override these settings, and any other default paths, such as a lookup of dynamic libraries inside /usr/lib and similar default locations.

If you are using older versions of GDB you must run with the full path to the executable. Later versions allow you to pass the bundle name on the command line.

Combining Libraries

If you want to build a new dynamic library combining the Qt 4 dynamic libraries, you need to introduce the ld -r flag. Then relocation information is stored in the output file, so that this file could be the subject of another ld run. This is done by setting the -r flag in the .pro file, and the LFLAGS settings.

Initialization Order

dyld(1) calls global static initializers in the order they are linked into the application. If a library links against Qt and references the globals in Qt (from global initializers in your own library), link the application against Qt before linking it against the library. Otherwise the result will be undefined because Qt's global initializers have not been called yet.

Compile-Time Flags

The following flags are helpful when you want to define macOS specific code:

  • Q_OS_DARWIN is defined when Qt detects you are on a Darwin-based system such as macOS or iOS.
  • Q_OS_MACOS is defined when you are on an macOS system.

Note: Q_WS_MAC is no longer defined in Qt 5.

If you want to define code for specific versions of macOS, use the availability macros defined in /usr/include/AvailabilityMacros.h.

The QSysInfo documentation has information about runtime version checking.

macOS Native API Access

Accessing the Bundle Path

macOS applications are structured as a directory (ending with .app). This directory contains sub-directories and files. It may be useful to place items, such as plugins and online documentation, inside this bundle. The following code returns the path of the application bundle:

#ifdef Q_OS_MAC
    CFURLRef appUrlRef = CFBundleCopyBundleURL(CFBundleGetMainBundle());
    CFStringRef macPath = CFURLCopyFileSystemPath(appUrlRef,
                                           kCFURLPOSIXPathStyle);
    const char *pathPtr = CFStringGetCStringPtr(macPath,
                                           CFStringGetSystemEncoding());
    qDebug("Path = %s", pathPtr);
    CFRelease(appUrlRef);
    CFRelease(macPath);
#endif

Note: When macOS is set to use Japanese, a bug causes this sequence to fail and return an empty string. Therefore, always test the returned string.

For more information about using the CFBundle API, visit Apple's Developer Website.

QCoreApplication::applicationDirPath() can be used to determine the path of the binary within the bundle.

Translating the Application Menu and Native Dialogs

The items in the Application Menu will be merged correctly for localized applications, but they will not show up translated until the application bundle contains a localized resource folder. to the application bundle.

Essentially, there needs to be a file called locversion.plist. Here is an example of an application with Norwegian localization:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN"
"http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>LprojCompatibleVersion</key>
    <string>123</string>
    <key>LprojLocale</key>
    <string>no</string>
    <key>LprojRevisionLevel</key>
    <string>1</string>
    <key>LprojVersion</key>
    <string>123</string>
</dict>
</plist>

Afterwards, when the application is run with the preferred language set to Norwegian, the menu items should display Avslutt instead of Quit.

The Bundle Programming Guide contains information about bundles and the localized resource folder.

Mixing Qt with Native Code

Two classes are available for adding native Cocoa views and controls inside a Qt application, or for embedding Qt into a native Cocoa application: QMacCocoaViewContainer, and QMacNativeWidget.

Using Native Cocoa Panels

Qt's event dispatcher is more flexible than what Cocoa offers, and lets the user spin the event dispatcher (and running QEventLoop::exec) without having to think about whether or not modal dialogs are showing on screen (which is a difference compared to Cocoa). Therefore, we need to do extra management in Qt to handle this correctly, which unfortunately makes mixing native panels hard. The best way at the moment to do this, is to follow the pattern below, where we post the call to the function with native code rather than calling it directly. Then we know that Qt has cleanly updated any pending event loop recursions before the native panel is shown:

#include <QtGui>

class NativeProxyObject : public QObject
{
    Q_OBJECT
public slots:
    void execNativeDialogLater()
    {
        QMetaObject::invokeMethod(this, "execNativeDialogNow", Qt::QueuedConnection);
    }

    void execNativeDialogNow()
    {
        NSRunAlertPanel(@"A Native dialog", @"", @"OK", @"", @"");
    }

};

#include "main.moc"

int main(int argc, char **argv){
    QApplication app(argc, argv);
    NativeProxyObject proxy;
    QPushButton button("Show native dialog");
    QObject::connect(&button, SIGNAL(clicked()), &proxy, SLOT(execNativeDialogLater()));
    button.show();
    return app.exec();
}

Limitations

Fink

If you have installed the Qt for X11 package from Fink, it will set the QMAKESPEC environment variable to darwin-g++. This will cause problems when you build the Qt for macOS package. To fix this, simply unset your QMAKESPEC or set it to macx-g++ before you run configure. To get a fresh Qt distribution, run make confclean in the command-line.

MySQL and macOS

There seems to be a issue when both -prebind and -multi_module are defined when linking static C libraries into dynamic libraries. If you get the following error message when linking Qt:

ld: common symbols not allowed with MH_DYLIB output format with the -multi_module option
/usr/local/mysql/lib/libmysqlclient.a(my_error.o) definition of common _errbuff (size 512)
/usr/bin/libtool: internal link edit command failed

re-link Qt using -single_module. This is only a problem when building the MySQL driver into Qt. It does not affect plugins or static builds.

D-Bus and macOS

The QtDBus module defaults to dynamically loading the libdbus-1 library on macOS. That means applications linking against the QtDBus module will load even on macOS systems that do not have the libraries, but they will fail to connect to any D-Bus server and they will fail to open a server using QDBusServer.

To use D-Bus functionality, you need to install the libdbus-1 library, for example through Homebrew, Fink or MacPorts. You may want to include those libraries in your application's bundle if you're deploying to other systems. Additionally, note that there is no system bus on macOS and that the session bus will only be started after launchd is configured to manage it.

Menu Actions

  • Actions in a QMenu with accelerators that have more than one keystroke (QKeySequence) will not display correctly, when the QMenu is translated into a Mac native menu bar. The first key will be displayed. However, the shortcut will still be activated as on all other platforms.
  • QMenu objects used in the native menu bar are not able to handle Qt events via the normal event handlers. Install a delegate on the menu itself to be notified of these changes. Alternatively, consider using the QMenu::aboutToShow() and QMenu::aboutToHide() signals to keep track of menu visibility; these provide a solution that should work on all platforms supported by Qt.

Native Widgets

Qt has support for sheets, represented by the window flag, Qt::Sheet.

Usually, when referring to a native macOS application, native means an application that interfaces directly to the underlying window system, rather than one that uses some intermediary layer. Qt applications run as first class citizens, just like Cocoa and Carbon applications. We use Cocoa internally to communicate with the operating system.

© 2017 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.