2015-05-14 155 views
1

我正在使用PyQt4中包含通過使用2D陣列matplotlib的imshow顯示圖像的GUI。如果我用pyplot顯示它,如果將鼠標移動到圖像上,窗口將顯示光標的x,y座標。但是,當我將imshow嵌入到pyqt GUI中時,這似乎消失了。有沒有一種方法可以讓鼠標事件調用某個函數,該函數會返回鼠標懸停點的x,y座標(或者更好,還有那個二維數組的索引)?matplotlib GUI imshow座標

編輯:我找到了wx的文檔,但我仍然不知道如何爲我的GUI做到這一點。 wxcursor_demo

如果有幫助,這裏是我如何嵌入imshow情節。首先,我創建一個基畫布類,然後從該我創建一個類用於imshow:

class Canvas(FigureCanvas): 
    def __init__(self, parent = None, width = 5, height = 5, dpi = 100, projection = None): 
     self.fig = Figure(figsize = (width, height), dpi = dpi) 
     if projection: 
      self.axes = Axes3D(self.fig) 
     else: 
      self.axes = self.fig.add_subplot(111) 

     self.axes.tick_params(axis = 'both', which = 'major', labelsize = 8) 
     self.axes.tick_params(axis = 'both', which = 'minor', labelsize = 8) 
     self.compute_initial_figure() 
     FigureCanvas.__init__(self, self.fig) 
     self.setParent(parent) 
     FigureCanvas.setSizePolicy(self, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) 
     FigureCanvas.updateGeometry(self) 

    def compute_initial_figure(self): 
     pass 

class TopView(Canvas): 
    def __init__(self, *args, **kwargs): 
     Canvas.__init__(self, *args, **kwargs) 
     self.divider = make_axes_locatable(self.axes) 
     self.cax = self.divider.append_axes("bottom", size = "5%", pad = 0.2) 

    def compute_initial_figure(self): 
     self.top = self.axes.imshow(zarr, interpolation = 'none', extent = [xmin, xmax, ymin, ymax], origin = 'lower') 
     self.top.set_cmap('nipy_spectral') 
     self.top.set_clim(vmin = pltMin, vmax = pltMax) 

然後,在主窗口中,我創建對象,並將其放置在網格佈局:

tv = TopView(self.main_widget, width = 4, height = 3, dpi = 100) 
self.g.addWidget(tv, 1, 2, 3, 1) 

回答

1

Matplotlib使用自己的事件,以便它們獨立於UI工具包(wx-windows,Qt等)。因此wxcursor_demo很容易適應Qt,就像你的情況一樣。

首先將下面一行添加到您的Canvas類的構造函數

self.mpl_connect('motion_notify_event', self.mouse_moved) 

這會在每次鼠標在移動時調用MOUSE_MOVED方法。

mouse_moved方法可以發出連接到它知道如何顯示鼠標座標的插件一個Qt信號。事情是這樣的:

def mouse_moved(self, mouse_event): 
    if mouse_event.inaxes: 
     x, y = mouse_event.xdata, mouse_event.ydata 
     self.mouse_moved_signal.emit(x,y) 

當然,你必須在Canvas構造函數定義mouse_moved_signal爲好。請注意,mouse_event參數是一個Matplotlib event,而不是Qt事件。

我建議你Matplotlib文檔中讀取chapter about events瞭解什麼是可能的。