pythonpyqt5mouseeventpyqtgraphviewbox

PyQtGraph disable mouse wheel, but leave other functions of the mouse untouched


I have a pyqtgraph.ViewBox widget with an image in it. The mouse is enabled, so I can select a rectangle on the image and it will be zoomed. But there is an unwanted feature, the zooming occurs on the mouse wheel scrolling aswell.

How can I disable the mouse wheel only, and leave the rest as is?

from PyQt5.QtWidgets import QApplication, QMainWindow
import pyqtgraph as pg
import cv2


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        pg.setConfigOption('imageAxisOrder', 'row-major')
        pg.setConfigOption('leftButtonPan', False)  # if False, then dragging the left mouse button draws a rectangle
    
        self.grid = pg.GraphicsLayoutWidget()
        self.top_left = self.grid.addViewBox(row=1, col=1)

        image = cv2.imread('/path/to/your/image.jpg', cv2.IMREAD_UNCHANGED)
        self.image_item = pg.ImageItem()
        self.image_item.setImage(image)
        self.top_left.addItem(self.image_item)

        self.setCentralWidget(self.grid)


def main():
    app = QApplication([])
    window = MainWindow()
    window.show()
    app.exec_()


if __name__ == '__main__':
    main()

Solution

  • You can install an event filter on the ViewBox and catch the mouse wheel event, in this case QEvent.GraphicsSceneWheel.

    from PyQt5.QtWidgets import QApplication, QMainWindow
    from PyQt5.QtCore import QEvent
    import pyqtgraph as pg
    import cv2
    
    
    class MainWindow(QMainWindow):
        def __init__(self):
            super().__init__()
            pg.setConfigOption('imageAxisOrder', 'row-major')
            pg.setConfigOption('leftButtonPan', False)  # if False, then dragging the left mouse button draws a rectangle
        
            self.grid = pg.GraphicsLayoutWidget()
            self.top_left = self.grid.addViewBox(row=1, col=1)
            self.top_left.installEventFilter(self)
    
            image = cv2.imread('/path/to/your/image.jpg', cv2.IMREAD_UNCHANGED)
            self.image_item = pg.ImageItem()
            self.image_item.setImage(image)
            self.top_left.addItem(self.image_item)
    
            self.setCentralWidget(self.grid)
    
        def eventFilter(self, watched, event):
            if event.type() == QEvent.GraphicsSceneWheel:
                return True
            return super().eventFilter(watched, event)