You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Qt6中如何接收触摸事件?多触点无响应问题排查

Qt6 触摸事件处理问题排查与多触摸失效解决

一、初始触摸事件启用尝试及编译错误

  • 尝试在main.cpp中设置应用属性以启用触摸事件:

    QApplication::setAttribute(Qt::ApplicationAttribute::WA_AcceptTouchEvents);
    

    编译报错:error: no member named 'WA_AcceptTouchEvents' in 'Qt::ApplicationAttribute'
    IntelliSense索引显示该属性存在,但实际编译不通过,怀疑Qt Creator索引异常

  • 调整代码省略枚举类限定:

    QApplication::setAttribute(Qt::WA_AcceptTouchEvents);
    

    编译报错:error: cannot initialize a parameter of type 'Qt::ApplicationAttribute' with an rvalue of type 'Qt::WidgetAttribute'

  • 尝试在QOpenGLWindow构造函数中调用setAttribute:
    构造函数代码:

    OpenGLWindow::OpenGLWindow()
    {
        setTitle("OpenGL ES 2.0, Qt6, C++");
        resize(350, 350);
        setAttribute(Qt::WA_AcceptTouchEvents);
    }
    

    编译报错:error: use of undeclared identifier 'setAttribute'; did you mean 'QInputMethodEvent::Attribute'?

二、项目pro文件配置

QT += core gui opengl widgets

CONFIG += c++17

# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
# disables all the APIs deprecated before Qt 6.0.0
# DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000

SOURCES += \
    main.cpp \
    opengl_window.cpp

HEADERS += \
    opengl_window.h

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

三、重写touchEvent后多触摸失效问题

根据Qt官方文档说明:

Unlike widgets, QWindows receive touch events always, there is no need to opt in. When working directly with a QWindow, it is enough to reimplement QWindow::touchEvent()

重写touchEvent代码如下:

void OpenGLWindow::touchEvent(QTouchEvent *event)
{
    switch (event->type())
    {
        case QEvent::TouchBegin:
            qDebug() << "counter = " << m_counter;
            m_counter++;
            break;
    }
}

真机运行时出现异常:单指触摸屏幕会打印counter = 0,但按住一根手指再用另一根手指触摸时,不会触发counter = 1的打印,多触摸功能未生效。

内容的提问来源于stack exchange,提问作者8Observer8

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 02:13:37