Search code examples
c++objective-cqtqt-creatorappkit

How do I use Objective-C variables and methods for a Qt window on macOS?


I have the following code in a Qt project, and I want to set the titlebarAppearsTransparent variable for a window to true in Objective-C. The program compiles correctly, but it crashes when it reaches [&w titlebarAppearsTransparent:YES]; Is what I'm trying to do even possible, and if so how do I fix it?

#include "mainwindow.h"
#include <QApplication>
#include <QFile>
#include <QDebug>
#include <QDir>
#include "globals.h"

#import <Foundation/Foundation.h>
#import <AppKit/AppKit.h>
#import <AppKit/NSWindow.h>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QApplication::setOrganizationName("Siddha Tiwari");
    QApplication::setApplicationName("NarwhalEdit");

    MainWindow *w = new MainWindow();

    [&w titlebarAppearsTransparent:YES];

    setTheme(true);

    w->show();

    return a.exec();
}

Solution

  • It is possible to accomplish this using the native API, as reported here, obtaining the NSWindow pointer from QWidget::window()::winId().

    I would also suggest to wrap the code with conditional compiling directives, so it is ignored when compiling for other platforms.

    Here is a snippet (assuming w is the pointer to your QMainWindow):

    #ifdef Q_OS_MAC
    
    QCoreApplication::setAttribute( Qt::AA_DontCreateNativeWidgetSiblings );
    NSView *nsview = ( __bridge NSView * )reinterpret_cast<void *>( w->window()->winId() );
    NSWindow *nswindow = [nsview window];
    nswindow.titlebarAppearsTransparent = YES;
    
    #endif