objective-c - QT运行objective-c代码

标签 objective-c qt

我正在尝试在我的 Mac 应用程序上运行 native object-c 代码。

我的代码如下:

主窗口.h:

#ifdef Q_OS_MAC
    #include <Carbon/Carbon.h>
    #include <ctype.h>
    #include <stdlib.h>
    #include <stdio.h>

    #include <mach/mach_port.h>
    #include <mach/mach_interface.h>
    #include <mach/mach_init.h>

    #include <IOKit/pwr_mgt/IOPMLib.h>
    #include <IOKit/IOMessage.h>
#endif

主窗口.cpp:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);


    #ifdef Q_OS_MAC
    [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver: self
            selector: @selector(receiveSleepNote:)
            name: NSWorkspaceWillSleepNotification object: NULL];
    #endif

}

#ifdef Q_OS_MAC
- (void) receiveSleepNote: (NSNotification*) note
{
    NSLog(@"receiveSleepNote: %@", [note name]);
}
#endif

但是我得到的错误似乎是 QT 不理解代码结构:

application.cpp: error: expected external declaration - (void) receiveSleepNote: (NSNotification*) note ^

最佳答案

为了使用 C++ 编译 objective-c,您需要将 objective-c 代码放在 .m 或 .mm 文件中。

随附的 header 可以包含可以从 C++ 调用的函数,这些函数的主体可以包含 objective-c 代码。

比方说,我们想调用一个函数来弹出 OSX 通知。从标题开始:-

#ifndef __MyNotification_h_
#define __MyNotification_h_

#include <QString>

class MyNotification
{
public:
    static void Display(const QString& title, const QString& text);    
};    

#endif

如您所见,这是 header 中的一个常规函数,可以从 C++ 中调用。这是实现:-

#include "mynotification.h"
#import <Foundation/NSUserNotification.h>
#import <Foundation/NSString.h>

void MyNotification::Display(const QString& title, const QString& text)
{
    NSString*  titleStr = [[NSString alloc] initWithUTF8String:title.toUtf8().data()];
    NSString*  textStr = [[NSString alloc] initWithUTF8String:text.toUtf8().data()];

    NSUserNotification* userNotification = [[[NSUserNotification alloc] init] autorelease];
    userNotification.title = titleStr;
    userNotification.informativeText = textStr;

    [[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification:userNotification];
}

该实现包含 objective-c,并且由于其 .mm 文件扩展名,编译器将正确处理它。

请注意,在问题中提供的示例中,您需要考虑代码在做什么;特别是在使用“self”时,因为我预计它需要引用 Objective-C 类,而不是 C++ 类。

关于objective-c - QT运行objective-c代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23404158/

相关文章:

ios - 在保持准确性的同时将 double 转换为 NSDecimalNumber

c++ - Qt中的实时像素绘制

c++ - 如何在不导致内存泄漏的情况下使用 QSGGeometryNode 并确保正确清理

c++ - QT - 指向全局内存的指针

iphone - 自定义 UITextField

objective-c - Cocoa 在分发时保存文本文件

ios - NSURLConnection不返回任何数据

ios - NSURLSessionTask 设置参数与 NSDictionary

Qt绘制的内容丢失

c++ - 在 Eclipse 中设计 Qt + OpenGL 应用程序