QGraphicsitem sceneEvent handler

QGraphicsitem sceneEvent handler

本文关键字:handler sceneEvent QGraphicsitem      更新时间:2023-10-16

我试图实现的是以下内容:

有一个QGraphicsitem,我可以用鼠标或手指按下并拖动它,所以它的颜色会根据拖动逐渐改变。

我还想使用触摸事件调整它的大小。

我已经完成了所有与鼠标相关的事件处理程序,如mousePressEvent,mouseMoveEvent和mouseReleaseEvent。在Windows下,触摸事件似乎默认转换为鼠标事件。

现在,我添加以下代码来重新实现 graphicItem 的 sceneEvent 函数:

bool MapGraphicItem::sceneEvent(QEvent * event)
    {
        switch (event->type()) {
        case QEvent::TouchBegin:
        case QEvent::TouchUpdate:
        case QEvent::TouchEnd:
            QTouchEvent *touchEvent = static_cast<QTouchEvent *>(event);
            QList<QTouchEvent::TouchPoint> touchPoints = touchEvent->touchPoints();
            if (touchPoints.count() == 2) {
                //do the zoom
                }
            return true;
        }
        return QGraphicsItem::sceneEvent(event);
    }

缩放也可以工作,问题是在捏缩放期间,鼠标事件也会触发,因此更改了我不想要的颜色。

如何处理这个问题?

Qt确实会自动生成"合成"鼠标事件,以允许仅为鼠标设计的应用程序在触摸屏上工作。

要区分来自物理鼠标的事件和合成事件,您可以执行以下操作:

  1. 将图形项目的所有事件处理代码从 mousePressEvent、mouseMoveEvent 和 mouseReleaseEvent 移动到 sceneEvent 方法。您应该将案例添加到案例 QEvent::GraphicsSceneMousePress、QEvent::GraphicsSceneMouseMove 和 QEvent::GraphicsSceneMouseRelease 的 switch 语句中。
  2. 在上述场景事件案例中,检查您接收的事件是否来自物理鼠标而不是合成。为此,请将事件指针强制转换为 QGraphicsSceneMouseEvent* 并仅处理 source() 方法返回 Qt::MouseEventNotSynthesized 的事件

例:

bool MapGraphicItem::sceneEvent(QEvent * event)
{
    switch (event->type()) {
    case QEvent::GraphicsSceneMousePress:
        if (event && ((QGraphicsSceneMouseEvent*)event)->source() == Qt::MouseEventNotSynthesized)
            handleMousePress();
        return true;
    case QEvent::GraphicsSceneMouseMove:
        if (event && ((QGraphicsSceneMouseEvent*)event)->source() == Qt::MouseEventNotSynthesized)
            handleMouseMove();
        return true;
    case QEvent::GraphicsSceneMouseRelease:
        if (event && ((QGraphicsSceneMouseEvent*)event)->source() == Qt::MouseEventNotSynthesized)
            handleMouseRelease();
        return true;
    // i left the rest of your while block unchanged
    case QEvent::TouchBegin:
    case QEvent::TouchUpdate:
    case QEvent::TouchEnd:
        QTouchEvent *touchEvent = static_cast<QTouchEvent *>(event);
        QList<QTouchEvent::TouchPoint> touchPoints = touchEvent->touchPoints();
        if (touchPoints.count() == 2) {
            //do the zoom
            }
        return true;
    }
    return QGraphicsItem::sceneEvent(event);
}