PyQtGraph禁用鼠标滚轮,但保持鼠标的其他功能不变

问题描述

我有一个带有图像的pyqtgraph.ViewBox小部件。启用了鼠标,因此我可以在图像上选择一个矩形,它将被缩放。但是有一个不需要的功能,缩放也会在鼠标滚轮滚动时发生。

如何仅禁用鼠标滚轮,而其余部分保持原样?

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()

解决方法

您可以在ViewBox上安装事件过滤器,并捕获鼠标滚轮事件,在这种情况下为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)
,

它比公认的答案简单得多。在 ViewBox 上使用 setMouseEnabled:

$ git update-index --assume-unchanged "temp_*.xml"

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...