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
The Aqua style is an essential part of the macOS platform. As with Cocoa, Qt provides widgets that look like those described in the macOS Human Interface Guidelines. Note that although Qt's widgets use AppKit under the hood for look and feel, it does not represent each individual Qt Widget as a wrapped native control.
The Qt Widget Gallery page contains sample images of applications 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:
- Qt::AA_PluginApplication
- Qt::AA_DontUseNativeMenuBar
- Qt::AA_MacDontSwapCtrlAndMeta
- Qt::WA_MacOpaqueSizeGrip
- Qt::WA_MacShowFocusRect
- Qt::WA_MacNormalSize
- Qt::WA_MacSmallSize
- Qt::WA_MacMiniSize
- Qt::WA_MacAlwaysShowToolWindow
- Qt::Sheet
- Qt::Drawer
- Qt::MacWindowToolBarButtonHint,
- QMainWindow::unifiedTitleAndToolBarOnMac
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.
Internationalization
Applications on macOS declare their supported languages as part of the Info.plist
of the application. The system will then match the application's supported languages with the user's language preferences to determine the locale the application is launched in. This in turn determines the ordered languages reflected through QLocale::uiLanguages(), and how system frameworks such as AppKit pick up their localized resources, such as menu titles and strings.
As Qt apps are not translated out of the box, the default generated Info.plist
for CMake
and qmake
projects sets CFBundleAllowMixedLocalizations
to YES
, to allow system frameworks to pick the localization that best matches the user's language preferences, even if that localization is not available for the application itself. Once you add translations to your application via qt_add_translations, the CFBundleAllowMixedLocalizations
key will be automatically removed, and replace with CFBundleLocalizations
, listing all the languages you support. For qmake
this process must be done manually.
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:
- If the window has a QMenuBar, then it is used.
- 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).
- 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 satisfied. 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.
Combining Libraries
If you want to build a new dynamic library combining the Qt 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 and later.
If you want to define code for specific versions of macOS, use the availability macros defined in /usr/include/AvailabilityMacros.h.
The QSysInfo and QOperatingSystemVerison 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 QString bundlePath = QString::fromNSString(NSBundle.mainBundle.bundlePath); qDebug() << "Bundle path =" << bundlePath; #endif
For more information about using the NSBundle API, visit Apple's Developer Website.
QCoreApplication::applicationDirPath() can be used to determine the path of the binary within the bundle.
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
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.
- By default, Qt creates a native Quit menu item that will react to the
CMD+Q
shortcut. Creating a QAction for the QAction::QuitRole role will replace that menu item. Therefore, the replacement action should be connected to either the QCoreApplication::quit slot, or a custom slot that stops the application.
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 applications. We use Cocoa internally to communicate with the operating system.
Symbol visibility warnings
In the context of linking C++ libraries, functions and objects are referred to as symbols. Symbols can have either default
or hidden
visibility.
For performance reasons, Qt and many other libraries compile their sources using hidden
visibility by default, and only mark symbols with default
visibility when they are meant to be used in user projects.
Unfortunately the Apple linker can issue warnings when one library is compiled with hidden
visibility and a user project application or library is compiled with default
visibility.
If project developers want to silence the warning, they need to build their project code with hidden
visibility as well.
In CMake that can be done by adding the following code to the your CMakeLists.txt
:
set(CMAKE_CXX_VISIBILITY_PRESET hidden)
In qmake that can be done by adding the following code to your .pro
file:
CONFIG+=hide_symbols
In case if a project builds libraries, any symbols in the library that are meant to be used in another library or application will have to be explicitly marked with default
visibility. For example, that can be done by annotating such functions or classes with Q_DECL_EXPORT.
dSYM bundle missing in xcarchive created by a CMake Xcode project
Due to a bug in Xcode and certain CMake limitations, a CMake-generated Xcode project will fail to include an application's dSYM
bundle into an xcarchive
, during Xcode's archiving task.
Qt provides a workaround as an opt-in, so that the dSYM
bundle is included in the xcarchive
, but it comes with trade-offs. That is, the following CMake features will not work correctly:
- any
$<TARGET_FILE:app>
generator expressions might expand to an invalid path that does not lead to the app binary - the
CMAKE_RUNTIME_OUTPUT_DIRECTORY
variable and its associatedRUNTIME_OUTPUT_DIRECTORY
target property will be ignored even if set - other unknown issues
To mitigate the issues above, you can:
- only enable the workaround when you intend to create the
xcarchive
and not during project development - make sure you only add executables and libraries in the root project directory, and not in
add_subdirectory
calls.
To enable the workaround, configure the project with the following option:
cmake . -DQT_USE_RISKY_DSYM_ARCHIVING_WORKAROUND=ON
or set the variable in the project before any qt_add_executable
or qt_add_library
calls:
set(QT_USE_RISKY_DSYM_ARCHIVING_WORKAROUND ON) ... qt_add_executable(app)