我正在尝试使用FigureCanveQtAgg将Matplotlib图形嵌入到Qt窗口中。可以很好地工作,但是当我单击该图时,我很难区分左键单击和右键单击。
这里是我所做的工作的简单版本(一段时间前我在左键单击上遇到了问题,因此我已经回答了上一个问题,并将其粘贴到了这里:How to draw a circle on a FigureCanvasQTAgg on mouse click)。
from PySide2 import QtCore, QtGui, QtWidgets
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import numpy as np
class PainterCanvas(FigureCanvas):
def __init__(self, parent=None, width=5, height=4, dpi=100):
fig = Figure(figsize=(width, height), dpi=dpi)
FigureCanvas.__init__(self, fig)
self.setParent(parent)
self._instructions = []
self.axes = self.figure.add_subplot(111)
def paintEvent(self, event):
super().paintEvent(event)
painter = QtGui.QPainter(self)
painter.setRenderHint(QtGui.QPainter.Antialiasing, True)
width, height = self.get_width_height()
for x, y, rx, ry, br_color in self._instructions:
x_pixel, y_pixel_m = self.axes.transData.transform((x, y))
# In matplotlib, 0,0 is the lower left corner,
# whereas it's usually the upper right
# for most image software, so we'll flip the y-coor
y_pixel = height - y_pixel_m
painter.setBrush(QtGui.QColor(br_color))
painter.drawEllipse( QtCore.QPoint(x_pixel, y_pixel), rx, ry)
def create_oval(self, x, y, radius_x=5, radius_y=5, brush_color="red"):
self._instructions.append([x, y, radius_x, radius_y, brush_color])
self.update()
class MyPaintWidget(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.canvas = PainterCanvas()
self.canvas.mpl_connect("button_press_event", self._on_left_click)
x = np.arange(0, 10, 0.1)
y = np.cos(x)
self.canvas.axes.plot(x, y)
layout_canvas = QtWidgets.QVBoxLayout(self)
layout_canvas.addWidget(self.canvas)
def _on_left_click(self, event):
self.canvas.create_oval(event.xdata, event.ydata, brush_color="green")
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = MyPaintWidget()
w.show()
sys.exit(app.exec_())
对于我当时想要的东西,它非常有用。但是,现在我需要区分左键单击和右键单击。我认为问题是因为函数mpl_connect()
只能使用“ button_press_event”事件。但是,有没有办法区分左键和右键?
我要实现的是:-如果用户单击鼠标左键:它将像现在一样绘制一个绿色圆圈-如果用户右键单击:它将打开带有功能的上下文菜单
谢谢!
您可以使用button
中event
的MyPaintWidget._on_left_click
属性来确定按下了哪个按钮。此属性是类型为matplotlib.backend_bases.MouseButton
的枚举常量。因此,要区分左键和右键按下,您可以执行以下操作]
matplotlib.backend_bases.MouseButton