1

我已经在 qt 中使用 NSUserNotification 和 NSUserNotificationCenter 实现了 UserNotificationAlert。我已经编写了在单击 actionButton 时执行操作的代码,但不幸的是它没有被执行。我有以下代码。

XYZ.h

namespace ABC {
void sendUserAlert(const QString &title, const QString &subTitle, const QString &actionButtonTitle, const QString &otherButtonTitle);
}

XYZ.mm

namespace ABC {

void sendUserAlert(const QString &title, const QString &subTitle, const QString &actionButtonTitle, const QString &otherButtonTitle)
        {
            @autoreleasepool {
                NSUserNotification *notification = [[NSUserNotification alloc] init];
                NSUserNotificationCenter *center = [NSUserNotificationCenter defaultUserNotificationCenter];
                [notification setTitle: title.toNSString()];
                if( !subTitle.isEmpty() ) {
                    [notification setSubtitle: subTitle.toNSString()];
                }
                if( !actionButtonTitle.isEmpty()) {
                    [notification setActionButtonTitle: actionButtonTitle.toNSString()];
                }
                if ( !otherButtonTitle.isEmpty()) {
                    [notification setOtherButtonTitle: otherButtonTitle.toNSString()];
                }
                [center deliverNotification:notification];
            }
        }
}

代表.mm

@interface HPObserver : NSObject<NSUserNotificationCenterDelegate>
     - (id) init;
     - (void) dealloc;
     - (void) applicationDidFinishLaunching: (NSNotification *)aNotification;
@end

@implementation HPObserver
- (id) init
{
    self = [super init];
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    [nc addObserver:self
            selector:@selector(applicationDidFinishLaunching:)
            name: NSApplicationDidFinishLaunchingNotification
            object: NSApp];
    return self;
}

- (void) dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc];
}

- (void) applicationDidFinishLaunching:(NSNotification *)aNotification
{
        @autoreleasepool {
        NSUserNotification *notification = [[aNotification userInfo] objectForKey:NSApplicationLaunchUserNotificationKey];
         if (notification.activationType == NSUserNotificationActivationTypeActionButtonClicked) {
            NSlog(@"Hello World");  
        }
    }
}

主文件

using namespace ABC;
int main(int argc, char **argv)
{
QString title = QObject::tr("Do you want to close the window");
QString actionButtonTitle = QObject::tr("Yes");
QString otherButtonTitle = QObject::tr("No");

ABC::sendUserAlert(title,subTitle,actionButtonTitle,otherButtonTitle);
}

显示 userNotification 但是当我单击“是”按钮时没有任何操作。我想我缺少将委托与主要功能联系起来,但我不知道该怎么做。请帮我解决这个问题。

4

0 回答 0