為matplotlib生成的圖添加編輯條,我們導入NavigationToolbar2QT
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT
繼承關系:

其中,NavigationToolbar2是實現NavigationToolbar2QT有關編輯條的主要實現類,下面對NavigationToolbar2進行詳細分析。
涉及zoom功能的有四個函數: zoom(), press_zoom(), drag_zoom(), release_zoom()
涉及pan功能的四個函數與之類似.
-
zoom()
鼠標按下事件綁定 press_zoom(),鼠標釋放事件綁定release_zoom()
-
press_zoom()
判斷是鼠標左鍵還是右鍵觸發的點擊事件,存入self._button_pressed中(1: 左鍵;2: 右鍵)。
關鍵代碼分析: 將鼠標點擊的坐標(x, y)、figure中的axes對象,i(含義不明), axes對象的rect(xmin, xmax, ymin, ymax)append(添加)到self._xypress中,代碼如下:
self._xypress.append((x, y, a, i, a._get_view()))
鼠標點擊事件綁定_switch_on_zoom_mode()以確認zoom縮放模式(左鍵縮小/右鍵放大)
鼠標拖動事件綁定drag_zoom()
鼠標釋放事件綁定_switch_off_zoom_mode()清除zoom縮放模式的設置
-
drag_zoom()
讀取self._xypress中的記錄(press_zoom中有詳細參數介紹),限制繪制區域(不超出Axes對象)
根據讀取的參數繪制矩形區域,
self.draw_rubberband(event, x1, y1, x2, y2)
-
release_zoom()
取消press_zoom()中注冊的事件,移除drag_zoom()中繪制的矩形
添加功能: 無視5像素之下的zoom操作,檢測共享xy軸的圖形
根據self._button_pressed設置in/out(縮放/放大)
關鍵代碼分析: 繪制一個指定的axes區域;參數: [lastx], [lasty]: press(按下)的坐標;[x], [y]: release(釋放鼠標)的坐標;[direction]:‘in’: 左鍵,‘out’:右鍵;
[self._zoom_mode]: ‘x’:x方向,‘y’:y方向;[twinx], [twiny]: 關於共享坐標軸的圖像顯示(未深入研究)。
a._set_view_from_bbox((lastx, lasty, x, y), direction,self._zoom_mode, twinx, twiny)
Other method:
push_current(): Push the current view limits and position onto the stack
save_figure(): Save the current figure.(override require)
draw(): Redraw the canvases, update the locators.
set_message(): Display a message on toolbar or in status bar.
back(), forward(): move back/forward up the view lim stack
home(): Restore the original view.
set_history_buttons(): Enable or disable the back/forward button.
press(): Called whenever a mouse button is pressed.
draw_rubberband(self, event, x0, y0, x1, y1), remove_rubberband(): Draw/Remove a rectangle rubberband to indicate zoom limits (not guaranteed that ``x0 <= x1`` and ``y0 <= y1`)
