Zooming/Scrolling issue with QWheel Event
-
Hello everyone,
I am currently trying to implement a zooming effect for my central QTextEdit by using QWheel event. However, I am facing an issue.
When I try to zoom in/out, the zoom effect works as expected. But when I use the mouse wheel, the scroll bar is being invoked as well, causing the QTextEdit to scroll up and down. I don't want this to happen as I want the position to remain the same and only to zoom in/out.
Code of MainWindow.cpp:
void MainWindow::wheelEvent(QWheelEvent *event) { bool controlKeyIsHeld = QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier); // If vertical mouse wheel goes up, then zoom in. if(event->angleDelta().y() > 0 && controlKeyIsHeld) { ui->QTextEdit_TextEdit->zoomIn(1); } else if(event->angleDelta().y() < 0 && controlKeyIsHeld) { ui->QTextEdit_TextEdit->zoomOut(1); } }
Here is the virtual method in MainWindow.h:
protected: void wheelEvent(QWheelEvent *event) override;
-
@jsulm Thank you so much. Your solution works perfectly.
Here is the code if anyone is interested:
QTextEditSubClass.h:
#ifndef QTEXTEDITSUBCLASS_H #define QTEXTEDITSUBCLASS_H #include <QTextEdit> class QTextEditSubClass : public QTextEdit { Q_OBJECT public: explicit QTextEditSubClass(QWidget *parent = 0); ~QTextEditSubClass(); // QWidget interface protected: void wheelEvent(QWheelEvent *event) override; }; #endif // QTEXTEDITSUBCLASS_H
QTextEditSubClass.cpp:
#include "qtexteditsubclass.h" #include "qapplication.h" #include "qevent.h" QTextEditSubClass::QTextEditSubClass(QWidget *parent) { } QTextEditSubClass::~QTextEditSubClass() { } void QTextEditSubClass::wheelEvent(QWheelEvent *event) { bool controlKeyIsHeld = QGuiApplication::keyboardModifiers().testFlag(Qt::ControlModifier); // If vertical mouse wheel goes up, then zoom in. if(event->angleDelta().y() > 0 && controlKeyIsHeld) { this->zoomIn(1); return; } else if(event->angleDelta().y() < 0 && controlKeyIsHeld) { this->zoomOut(1); return; } QTextEdit::wheelEvent(event); }
After creating this sub class, we simply create a new instance of this class and pass it to the mainwindow central widget.
Hope this helps.
-