本页内容

本机接口

原生接口提供了对其所继承的类中属于原生或平台特有的 API 的访问能力。

这些接口位于QNativeInterface 命名空间中,涵盖了诸如访问底层本机句柄、采用现有本机句柄或提供特定于平台的API等用例。

用法示例

访问底层本机句柄

当原生平台上的某项功能未在 Qt 中公开时,访问由 Qt 维护的原生句柄并利用它们来调用原生 API 会非常有用。

例如,要在 macOS 上通过QNativeInterface::QCocoaGLContext 本机接口访问QOpenGLContext 的底层 NSOpenGLContext:

using namespace QNativeInterface;
if (auto *cocoaGLContext = glContext->nativeInterface<QCocoaGLContext>())
    [cocoaGLContext->nativeContext() makeCurrentContext];

可通过QOpenGLContext::nativeInterface() 访问器访问该原生接口,该访问器会确保所请求的接口可用,否则返回nullptr 。随后可通过nativeContext() 访问器访问底层的 NSOpenGLContext。

采用现有的原生句柄

在某些情况下,原生平台或其他工具包已创建了一个原生句柄,您希望将其传递给 Qt —— 即对现有句柄进行封装,而不是创建一个新的句柄。

例如,要采用现有的 NSOpenGLContext,并将其用于与 Qt 创建的上下文共享资源:

using namespace QNativeInterface;
QOpenGLContext *adoptedContext = QCocoaGLContext::fromNativeContext(nsOpenGLContext);
anotherContext->setShareContext(adoptedContext);

被采用的上下文由QNativeInterface::QCocoaGLContext 原生接口中的特定于平台的工厂函数创建。

访问特定于平台的 API

在某些情况下,某些 API 因过于特定于某个平台而无法包含在跨平台的 Qt 类中,但仍值得引入。这些 API 既可以通过nativeInterface() 访问器以与访问底层原生句柄相同的方式获取,也可以直接作为原生接口中的静态函数使用。

例如,要在 Windows 上获取 OpenGL 模块句柄:

using namespace QNativeInterface;
HMODULE moduleHandle = QWGLContext::openGLModuleHandle();

源代码和二进制兼容性

对于原生接口 API,不提供源代码或二进制兼容性保证,这意味着使用这些接口的应用程序仅保证能在其开发所基于的 Qt 版本上运行。

可用接口

有关所有可用接口的列表,请参阅QNativeInterface 命名空间。

QOpenGLContext

通过QOpenGLContext::nativeInterface() 调用。

QNativeInterface::QCocoaGLContext

macOS 上 NSOpenGLContext 的原生接口

QNativeInterface::QEGLContext

EGL 上下文的原生接口

QNativeInterface::QGLXContext

GLX 上下文的原生接口

QNativeInterface::QWGLContext

Windows 系统上 WGL 上下文的原生接口

QOffscreenSurface

通过 `QOffscreenSurface::nativeInterface()` 访问。

QNativeInterface::QAndroidOffscreenSurface

Android 系统上离屏表面的原生接口

QSGTexture

通过 `QSGTexture::nativeInterface()` 访问。

QNativeInterface::QSGD3D11Texture

提供对 Direct3D 11 纹理对象的访问并支持其采用

QNativeInterface::QSGD3D12Texture

提供对 Direct3D 12 纹理对象的访问并支持其采用

QNativeInterface::QSGMetalTexture

提供对 Metal 纹理对象的访问并支持其采用

QNativeInterface::QSGOpenGLTexture

提供对 OpenGL 纹理对象的访问并支持其采用

QNativeInterface::QSGVulkanTexture

提供对 Vulkan 图像对象的访问并支持其采用

© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.