Mac OS UserNotificationCenter in Qt

The goal is to display notifications (popup + notification center) in Mac Os.

Attemp # 1. Create files myclass.h + myclass.mm (using OBJECTIVE_SOURCES). I was able to add notifications to the notification center. But to create popups, I have to implement NSUserNotificationCenterDelegate: shouldPresentNotification. Naive implementation of the method and passing the class as a delegate throws an exception at compile time: it is of type * MyClass, whereas the setDelegate method requires an id

Attempt # 2. Define myclass using objective-c style with @interface directive and so on. Unfortunately, the compiler was unable to compile NSObject.h. It looks like the objective-c class is not supported in Qt and we are forced to use the C ++ class declaration.

Any ideas how to implement a given mac-os protocol in a C ++ class?

Working example

MyClass.h

class MyClass
{
public:
    void test();
}

      

MyClass.mm

void MyClass::test()
{
  NSUserNotification *userNotification = [[[NSUserNotification alloc] init] autorelease];
  userNotification.title = @"Title";
  userNotification.informativeText = @"Test message";
  [[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification:userNotification];
}

      


Trying to add pop-ups. Throws an exception in the setDelegate method

MyClass.h

class MyClass
{
public:
    explicit MyClass();
    void test();
    BOOL shouldPresentNotification(NSUserNotificationCenter *center, NSUserNotification *notification);
}

      

MyClass.mm

MyClass::MyClass()
{
    [[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate:this];
}

BOOL MyClass::shouldPresentNotification(NSUserNotificationCenter *center, NSUserNotification *notification)
{
    return YES;
}

void MyClass::test()
{
  NSUserNotification *userNotification = [[[NSUserNotification alloc] init] autorelease];
  userNotification.title = @"Title";
  userNotification.informativeText = @"Test message";
  [[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification:userNotification];
}

      

0


source to share


1 answer


The solution turned out to be simple: you just have to point this to the required protocol



MyClass::MyClass()
{
    id<NSUserNotificationCenterDelegate> self = (id<NSUserNotificationCenterDelegate>)this;
    [[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate:self]; 
}

BOOL MyClass::shouldPresentNotification(NSUserNotificationCenter *center, NSUserNotification *notification)
{
    return YES;
}

void MyClass::test()
{
  NSUserNotification *userNotification = [[[NSUserNotification alloc] init] autorelease];
  userNotification.title = @"Title";
  userNotification.informativeText = @"Test message";
  [[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification:userNotification];
}

      

0


source







All Articles