Qt 6 Linux平台下QApplication::platformNativeInterface()使用及报错解决
Qt 6 Linux(X11)平台下QApplication::platformNativeInterface()使用指南
编译错误解决
你遇到的error: invalid use of incomplete type ‘class QPlatformNativeInterface’,是因为QPlatformNativeInterface仅做了前向声明,未引入完整定义的头文件,直接调用其成员函数就会触发该错误。
必要头文件引入
需根据平台引入对应头文件,建议用Qt官方推荐的宏做平台判断:
- 必须包含
QPlatformNativeInterface的定义头:#include <QPlatformNativeInterface> - 使用
QApplication时需包含:#include <QApplication> - X11平台下,要使用Xlib的
Display类型,需补充:
(#ifdef QT_CONFIG(x11) #include <QX11Info> #include <X11/Xlib.h> #endifQT_CONFIG(x11)比Q_OS_LINUX更精准,能区分Linux下的X11和Wayland环境)
X11平台的类型转换
QPlatformNativeInterface::display()返回的是void*,在X11平台下需要转换为Xlib的Display*类型,示例代码:
#ifdef QT_CONFIG(x11) auto nativeInterface = QApplication::platformNativeInterface(); Display* display = static_cast<Display*>(nativeInterface->display()); #endif
CMake构建配置
- 查找Qt6的必要模块:
find_package(Qt6 REQUIRED COMPONENTS Widgets Gui) - 查找X11依赖包:
find_package(X11 REQUIRED) - 为目标程序链接依赖库:
target_link_libraries(你的程序名称 PRIVATE Qt6::Widgets Qt6::Gui X11::X11 )
完整示例代码
#include <QApplication> #include <QPlatformNativeInterface> #ifdef QT_CONFIG(x11) #include <QX11Info> #include <X11/Xlib.h> #endif int main(int argc, char *argv[]) { QApplication app(argc, argv); #ifdef QT_CONFIG(x11) auto nativeInterface = QApplication::platformNativeInterface(); if (nativeInterface) { Display* display = static_cast<Display*>(nativeInterface->display()); // 在这里执行X11相关操作 } #endif return app.exec(); }
内容的提问来源于stack exchange,提问作者Igor Mironchik
相关产品推荐
相关产品推荐

