Qt5中如何获取QWindow对应的XCB连接且不依赖Qt5X11Extras?
Qt5获取指定QWindow对应XCB连接的实现方案
方案1:无Qt5X11Extras依赖实现(推荐)
虽然Qt官方标注QPlatformNativeInterface为非稳定API,但在Qt5全版本迭代周期内,X11平台下nativeResourceForWindow传入"connection"参数的返回值规则从未发生变动,实际兼容性有保障,且无需依赖libQt5X11Extras.so。
依赖头文件
#include <QGuiApplication> #include <QPlatformNativeInterface> #include <QWindow> #include <xcb/xcb.h>
实现代码
// 获取XCB连接指针 xcb_connection_t* getXcbConnectionFromWindow(QWindow* targetWindow) { if (!targetWindow || !targetWindow->platformWindow()) { return nullptr; } QPlatformNativeInterface* nativeInterface = qApp->platformNativeInterface(); if (!nativeInterface || qApp->platformName() != "xcb") { return nullptr; } return static_cast<xcb_connection_t*>(nativeInterface->nativeResourceForWindow("connection", targetWindow)); } // 同步获取窗口XID,用于wgpu创建交换链表面 uint32_t getXcbWindowId(QWindow* targetWindow) { if (!targetWindow || !targetWindow->platformWindow()) { return 0; } QPlatformNativeInterface* nativeInterface = qApp->platformNativeInterface(); if (!nativeInterface || qApp->platformName() != "xcb") { return 0; } return static_cast<uint32_t>(reinterpret_cast<quintptr>( nativeInterface->nativeResourceForWindow("xid", targetWindow) )); }
方案2:兼容兜底的条件编译方案
如果仍担心API变动风险,可以添加条件编译逻辑,实现不同环境的自动适配:
#ifdef QT_X11EXTRAS_LIB #include <QX11Info> xcb_connection_t* getXcbConnectionFromWindow(QWindow* targetWindow) { Q_UNUSED(targetWindow) return QX11Info::connection(); } uint32_t getXcbWindowId(QWindow* targetWindow) { return static_cast<uint32_t>(targetWindow->winId()); } #else // 插入方案1的实现代码 #endif
注意事项
- 调用上述方法前需确保
QWindow已完成初始化(已调用create()或show()方法),否则platformWindow指针为空会返回无效值 - 非X11平台(Wayland、Windows、macOS等)下方法会返回空指针,可通过
qApp->platformName() == "xcb"提前判断运行环境
内容的提问来源于stack exchange,提问作者Adrian Willenbüche
相关产品推荐
相关产品推荐

