python – Displaying a picture via QGraphicPixmapItem

Question:

Please help me, I am writing a GUI for displaying pictures ( Python3 + PyQt5 ).
Initially, I used QLabel and Pixmap , but I wanted to catch the mouse movement in order to change the picture later. And thought it was possible with QGraphicPixmapItem . But the movement of the mouse is not caught in any way.

Below is a schematic code.

from PyQt5.QtWidgets import QApplication, QMainWindow, QGraphicsItem
# и еще всякие разные импорты

# далее идет класс с Qt
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.GraphicPixmap = QtWidgets.QGraphicsPixmapItem()
        self.GraphicPixmap.setAcceptHoverEvents(True) #метод разрешает обработку событий 
        self.scene = QtWidgets.QGraphicsScene()
        self.scene.addItem(self.GraphicPixmap)
        self.graphicsView = QtWidgets.QGraphicsView(self.scene, self.centralwidget)
        #далее идет куча всякого Qt

class MainWindow_class(Ui_MainWindow, QMainWindow, QGraphicsItem):
    # класс со всякими функциями логики работы программы
    def __init__(self):
        super().__init__()
        self.setupUi(self)

    # функция должна отлавливать движение мышки по scene
    def hoverMoveEvent(self, event):
        print(event.pos())

if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv)
    ui = MainWindow_class()
    ui.show()
    sys.exit(app.exec_())

The main idea with a mouse is that I want to change it by clicking on the picture (the picture is a drawn graph that will change interactivity). Maybe someone knows how to nicely add some matplotlib with animation elements?

Answer:

You must register your hoverMoveEvent method with one or more hover handlers ( hoverEnterEvent , hoverLeaveEvent , hoverMoveEvent ).

Then the __init__ method will look like this:

def __init__(self):
    super().__init__()
    self.setupUi(self)
    self.GraphicPixmap.hoverMoveEvent = self.hoverMoveEvent
    self.GraphicPixmap.hoverEnterEvent = self.hoverMoveEvent
    self.GraphicPixmap.hoverLeaveEvent = self.hoverMoveEvent

For testing, I pre-placed Pixmap in GraphicPixmap :

self.pixmap = QPixmap("715.gif")
self.GraphicPixmap.setPixmap(self.pixmap)

Tested in Python 3.6, PyQt5 5.8.0, Windows 7 64-bit

Scroll to Top