I want to track the mouse's position over a matplot's canvas in real-time.
For now, I built a MplWidget that inherits the Qwidget (act like a container), then built a canvas over it to show the plot. However, the problem is that I can only track the mouse's position in the padding area except for the canvas area.
Since my canvas inherits the matplotlib.figure that is not a QWidget, thus it doesn't have the setMouseTracking() attribute. In this way, how to resolve this issue?
I found a quite useful link How to return mouse coordinates in realtime?. However, it also suffers the same issue. When the mouse is over the label (text area), the tracking function seems to be interrupted.
my code for this class shown here:
from PyQt5.QtWidgets import *
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
class MplWidget(QWidget):
def __init__(self, parent=None):
# QWidget.__init__(self, parent)
super(QWidget, self).__init__(parent)
self.canvas = FigureCanvas(Figure())
vertical_layout = QVBoxLayout()
vertical_layout.addWidget(self.canvas)
self.canvas.axes = self.canvas.figure.add_subplot(111)
self.setLayout(vertical_layout)
self.setMouseTracking(True)
def mouseMoveEvent(self, e):
text = "x: {0}, y: {1}".format(e.x(), e.y())
print(text)
super(MplWidget, self).mouseMoveEvent(e)
def mousePressEvent(self, e):
print('click!')
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…