2014-03-03 38 views
0

目標是在Mac Os中顯示通知(彈出窗口+通知中心)。Qt中的Mac OS UserNotificationCenter

Attemp#1。創建myclass.h + myclass.mm文件(使用OBJECTIVE_SOURCES)。我能夠將通知添加到通知中心。但爲了創建彈出窗口,我應該實現NSUserNotificationCenterDelegate:shouldPresentNotification。天真地實現該方法並將類傳遞爲委託引發編譯時異常:這是* MyClass類型,而setDelegate方法需要編號

嘗試#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]; 
} 
+0

你能提供一些代碼嗎? – trojanfoe

+0

添加到發表一些樣品 – developer

回答

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

有趣。那麼每個C++對象實例也是一個Objective-C對象? – trojanfoe

+0

據我瞭解Qt C++類以某種方式編譯到Objective-C中。雖然,也許我錯了 – developer

+0

不,這當然不是真的。 Qt類是純粹的C++,與Objective-C沒有任何關係。我很驚訝你的代碼工作。 – trojanfoe