nocturne
nocturne

Reputation: 647

How to detect mouse hover event in PySide6 widget

I am trying to create a custom image viewer widget with zoom to the mouse position. So far I have managed to detect mouse scroll events, but I cannot detect a mouse hover events so I could determine a mouse position to zoom to.

I seems to me that the mouse hover event is not even occurring. I tried to print out all events, but the QHoverEvent is just not there. The only event occurring during mouse hover is QEvent::ToolTip which has the mouse position but it only occurs after the mouse hovering stops and it has quite a delay (~0.5s).

Here is the code:

import sys
from PySide6 import QtWidgets
from PySide6.QtWidgets import QDialog, QVBoxLayout, QLabel
from PySide6.QtGui import QPixmap
from PySide6.QtCore import Qt
from PIL.ImageQt import ImageQt

class ImageViewer(QDialog):
    def eventFilter(self, object, event):
        print("Event:" + str(event))
        if str(event) == '<PySide6.QtGui.QWheelEvent(Qt::NoScrollPhase, pixelDelta=QPoint(0,0), angleDelta=QPoint(0,-120))>':
            print("detected zoom out")
        if str(event) == '<PySide6.QtGui.QWheelEvent(Qt::NoScrollPhase, pixelDelta=QPoint(0,0), angleDelta=QPoint(0,120))>':
            print("detected zoom in")
        if str(event) == '<PySide6.QtCore.QEvent(QEvent::ToolTip)>':
            print("detected tooltip")
        return True

    def __init__(self, img: ImageQt):
        super().__init__()
        self.setWindowTitle('Image viewer example')
        self.imageWidget = QLabel()
        self.imageWidget.setAlignment(Qt.AlignCenter)
        self.imageWidget.setPixmap(QPixmap.fromImage(img))
        self.layout = QVBoxLayout()
        self.layout.addWidget(self.imageWidget)
        self.setLayout(self.layout)
        self.imageWidget.installEventFilter(self)

if __name__ == '__main__':
    # prepare app
    app = QtWidgets.QApplication(sys.argv)

    # create viewer widget
    imageViewer = ImageViewer(ImageQt("img.png"))
    imageViewer.show()

    # close app
    sys.exit(app.exec())

I am able to detect the mouse scrolling, enter widget, leave, mouse button press/release, mouse move (with mouse pressed). But the mouse hover is just not there. Could someone tell me how to detect the mouse hover event (with mouse position info)?

Upvotes: 0

Views: 2948

Answers (1)

Antoine Nguyen
Antoine Nguyen

Reputation: 121

It works for me with self.setAttribute(Qt.WidgetAttribute.WA_Hover) in the __init__() constructor.

Upvotes: 3

Related Questions