Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How to use Qt3DRender::QObjectPicker with touch events on smartphones?



  • How to use Qt3DRender::QObjectPicker with touch event?

    I'm adding Qt3DRender::QObjectPicker component to my Qt3D entities like this:

    Qt3DRender::QObjectPicker *MyClass::createObjectPickerForEntity(Qt3DCore::QEntity *entity)
    {
        Qt3DRender::QObjectPicker *picker = new Qt3DRender::QObjectPicker(entity);
        picker->setHoverEnabled(false);
        entity->addComponent(picker);
        connect(picker, &Qt3DRender::QObjectPicker::pressed, this, &MyClass::handlePickerPress);
    
        return picker;
    }
    

    My object picker works with mouse clicks, but it doesn't work with touch events. Does anybody know how I can use Qt3D object picker with touch events on smartphones?



  • It can be done with QScreenRayCaster:

    /*
      * You have to add the ray caster to the root entity as a component
      * Perform ray casting tests by specifying "touch" coordinates in screen space
      */
        m_screenRayCaster = new Qt3DRender::QScreenRayCaster(m_rootEntity);
        m_screenRayCaster->setRunMode(Qt3DRender::QAbstractRayCaster::SingleShot);
        m_rootEntity->addComponent(m_screenRayCaster);
    
    /*
      * Handle ray casting results, e.g. by touch events
      */
        QObject::connect(m_screenRayCaster, &Qt3DRender::QScreenRayCaster::hitsChanged, this, &MyClass::handleScreenRayCasterHits);
    
    

    Triggering QScreenRayCaster by touch events:

    void MyClass::HandleTouchEvent(QTouchEvent *event)
    {
        switch (event->type()) {
        case QEvent::TouchBegin:
            break;
        case QEvent::TouchEnd:
            if (event->touchPoints().count() == 1) {
                QPointF point = event->touchPoints().at(0).pos();
                m_screenRayCaster->trigger(QPoint(static_cast<int>(point.x()), static_cast<int>(point.y())));
            }
            break;
        default:
            break;
        }
    
    }
    

    Handling ray casting results in a slot:

    void MyClass::handleScreenRayCasterHits(const Qt3DRender::QAbstractRayCaster::Hits hits)
    {
        for (int i = 0; i < hits.length(); ++i) {
            qDebug() << __func__ << "Hit Type: " << hits.at(i).type();
        }
    }
    

Log in to reply