Qt 5 : Mouse Wheel event behaviour for zooming image

丶灬走出姿态 提交于 2019-12-06 15:06:45

The code shows that you didn't subclass QGraphicsView, but instead use one in your own widget.

The wheel event will be first sent to the actual graphics view widget. There it is handled with Qt's default behaviour, namely scrolling. Only if you scrolled to the bottom, the graphics view cannot handle the wheel event, and it is propagated to its parent, your class. That's why you only can zoom when scrolled to the border.

To fix this, you should install an event filter. That allows you to intercept the wheel event and process it in your class:

// Outline, not tested
viewer::viewer(QWidget *parent) : QWidget(parent),ui2(new Ui::viewer)
{
    ui2->setupUi(this);
    // Let me handle your events
    ui2->graphicsView->installEventFilter(this);
} 

// should be protected
bool viewer::eventFilter(QObject *obj, QEvent *event) {
  if (event->type() == QEvent::GraphicsSceneWheel) {
      // Your implementation. 
      // You can't use QWheelEvent, as Graphicscene works with its own events...
     handleWheelOnGraphicsScene(static_cast<QGraphicsSceneWheelEvent*> (event));

     // Don't propagate
     return true;
  }

  // Other events should propagate
  return false;
}

Update
I just figured out that the event filter will not recieve GraphicsSceneWheel events on the graphics view. Instead, you have to install the filter on the Graphics Scene. Also, you have to call event->accept() so that it will not propagated.

So Updated Code:

// In Constructor, or where appropriate
ui2->graphicsView->scene()->installEventFilter(this);


bool viewer::eventFilter(QObject *obj, QEvent *event) {
    if (event->type() == QEvent::GraphicsSceneWheel) {
        handleWheelOnGraphicsScene(static_cast<QGraphicsSceneWheelEvent*> (event));

        // Don't propagate
        event->accept();
        return true;
    }
    return false;
}

also note that handleWheelOnGraphicsScene or whatever you want to call it, should be a private method, and doesn't have to be a slot.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!