Qt在Xcode原生Mac Cocoa应用中使用时的Could not find the Qt platform plugin问题

最近在测试Xcode原生Mac Cocoa GUI应用中直接调用Qt GUI时遇到了一个报错找不到native plugin的问题。先记录下操作系统是:macOS 13.4,Xcode版本是:Version 14.3 (14E222b),Qt版本是:6.8.0。用法是在Xcode中新建一个App,interface选的xib(但应该没关系,因为根本没用任何xcode GUI编辑功能),然后在生成的的代码项目中手动加入各种依赖的Qt Framework,并设置好include,lib,rpath等各种路径。代码也是从网上搜到的很简单的创建Qt空间后,通过winId的方式(这是Qt6新改的,以前的Qt5及旧版本需要使用QMacNativeWidget)挂到NSView下,如下:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    // Insert code here to initialize your application
    QPushButton* btn = new QPushButton("testtttttttttttt");
    NSView* viewBtn = (__bridge NSView*)((void*)btn->winId());
    [self.window.contentView addSubview:viewBtn];
    btn->show();
    [viewBtn setNeedsDisplay:YES];
    [self.window makeKeyAndOrderFront:self.window];
}

需要注意的是开了ARC后的winId返回到NSView*的cast,c cast,c++ cast直接用都不行,查了半天才找到这种__bridge cast配合强转void*的可行方式。

然后运行,发现了标题中的报错信息:

warning: 'QtCore' contains a debug script. To run this script in this debug session:

    command script import "/Users/test/Qt/6.8.0/macos/lib/QtCore.framework.dSYM/Contents/Resources/Python/QtCore.py"

To run all discovered debug scripts in this session:

    settings set target.load-script-from-symbol-file true

warning: 'QtCore' contains a debug script. To run this script in this debug session:

    command script import "/Users/test/Qt/6.8.0/macos/lib/QtCore.framework.dSYM/Contents/Resources/Python/QtCore.py"

To run all discovered debug scripts in this session:

    settings set target.load-script-from-symbol-file true

2025-03-09 11:24:47.194954+0800 wz_test[54966:6072461] [qt.core.plugin.factoryloader] checking directory path "/Users/test/Qt/6.8.0/macos/plugins/platforms" ...
2025-03-09 11:24:47.195117+0800 wz_test[54966:6072461] [qt.core.plugin.factoryloader] checking directory path "/Users/test/Library/Developer/Xcode/DerivedData/wz_test-fgfqwqlzesdkckbcqzfvzmkwxwuh/Build/Products/Debug/wz_test.app/Contents/MacOS/platforms" ...
2025-03-09 11:24:47.197443+0800 wz_test[54966:6072461] [qt.qpa.plugin] Could not find the Qt platform plugin "cocoa" in ""
2025-03-09 11:24:47.197606+0800 wz_test[54966:6072461] This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem.

上面的详细信息可能要增加环境变量QT_DEBUG_PLUGINS=1来开启,可以加在Xcode调试Run scheme中的环境变量里。一开始排查以为是某些运行时路径设置的有问题,报错的行为看起来是Qt运行时初始化时加载某些动态库组件失败造成的,于是顺着这个思路查,发现网上确实有不少相同问题,但是引导方向全是增加plugin的搜索环境变量,比如:QT_PLUGIN_PATH=/Users/test/Qt/6.8.0/macos/plugins/,或者QT_QPA_PLATFORM_PLUGIN_PATH=/Users/test/Qt/6.8.0/macos/plugins/platforms/ 这些,实测后发现debug信息中确实有按照环境变量指定的path去寻找plugin,但就是报could not find,明明libqcocoa.dylib就在那里,它就是说没有!

百思不解时看到了一个网上的文章,提到了某个Mac系统的sandbox设置可能影响这种运行时加载动态库的行为,于是修改了下app的entitlements配置,增加(或者修改已有)com.apple.security.app-sandbox=NO的设置,然后全clean,重新build,再次运行,问题解决。

博主友情提示:

如您在评论中需要提及如QQ号、电子邮件地址或其他隐私敏感信息,欢迎使用>>博主专用加密工具v3<<处理后发布,原文只有博主可以看到。