Qt QWheelEvent angleDelta不改变

时间:2019-05-14 15:18:20

标签: qt

我试图在鼠标滚轮移动时在程序中实现缩放功能。该代码似乎可以正常工作,除了无论我向上还是向下滚动滚轮都可以放大。

我调试打印了车轮的angleDelta,它是一个常数,很大的数字。我找不到在网上遇到同样问题的人。

bool MyClass::eventFilter(QObject *obj, QEvent *event)
{
    QWheelEvent* wheel_event = static_cast<QWheelEvent*>(event);
    switch (static_cast<int>(event->type()))
    {
    case QEvent::GraphicsSceneWheel:
    {
        if (QApplication::keyboardModifiers() & Qt::ControlModifier)
        {
            const QGraphicsView::ViewportAnchor anchor = view->transformationAnchor();
            view->setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
            int angle = wheel_event->angleDelta().y();
            qreal factor;

            qDebug() << "Ctrl + Wheel Event! Angle = " << angle << wheel_event->angleDelta().y() << wheel_event->pixelDelta().y() << wheel_event->delta() << wheel_event->angleDelta();

            if (angle > 0)
            {
                factor = 1.1;
            } else
            {
                factor = 0.9;
            }
            view->scale(factor, factor);
            view->setTransformationAnchor(anchor);
            break;
        }
    }
    }
}

我希望向下滚动时看到负数,但是无论滚动方向如何,我打印的所有值都不会改变。在此代码中,视图是指向QGraphicsView对象的指针。

1 个答案:

答案 0 :(得分:3)

如果为event->type() == QEvent::GraphicsSceneWheel,则实际事件类型为QGraphicsSceneWheelEvent 不是 QWheelEvent。因此,所示的代码具有未定义的行为。尝试(未试用)...

bool MyClass::eventFilter (QObject *obj, QEvent *event)
{
    if (event->type() == QEvent::GraphicsSceneWheel) {
        if (auto *wheel_event = static_cast<QGraphicsSceneWheelEvent*>(event)) {
            if (QApplication::keyboardModifiers() & Qt::ControlModifier) {
                const QGraphicsView::ViewportAnchor anchor = view->transformationAnchor();
                view->setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
                qreal factor;

                qDebug() << "Ctrl + Wheel Event! Delta = " << wheel_event->delta();

                if (wheel_event->delta() > 0) {
                    factor = 1.1;
                } else {
                    factor = 0.9;
                }
                view->scale(factor, factor);
                view->setTransformationAnchor(anchor);
            }
        }
    }

    /*
     * The following assumes `QObject` is the base class of MyClass.
     */
    return QObject::eventFilter(obj, event);
}