Qt中的Mac OS UserNotificationCenter

时间:2014-03-03 09:10:20

标签: macos qt objective-c++

目标是在Mac Os中显示通知(弹出+通知中心)。

尝试#1。创建myclass.h + myclass.mm文件(使用OBJECTIVE_SOURCES)。我能够向通知中心添加通知。但是为了创建弹出窗口,我应该实现NSUserNotificationCenterDelegate:shouldPresentNotification。天真地实现该方法并将类作为委托传递引发编译时异常:这是* MyClass类型,而setDelegate方法需要id

尝试#2。使用带有@interface指令的objective-c样式定义myclass,依此类推。不幸的是,编译器无法编译NSObject.h。看起来Qt中不支持class objective-c,我们不得不使用C ++类声明。

任何想法,如何在C ++类中实现给定的mac-os协议?

工作示例

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];
}

尝试添加弹出窗口。在setDelegate方法中引发异常

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];
}

1 个答案:

答案 0 :(得分:0)

解决方案变得简单:您应该将强制转换为必需的协议

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];
}