在PyQt窗口中绘制没有延迟的matplotlib矩形

时间:2016-03-31 10:37:08

标签: python matplotlib pyqt mouse box

当我点击鼠标时,我想要绘制一个方框。当我单击按钮移动鼠标时,框应该改变。现在,问题是除非我停止鼠标移动,否则盒子不会更新,因此动作似乎有点滞后。如果没有将绘图放在PyQt环境中,它就可以正常工作。但不幸的是,我需要在PyQt窗口中使用它。

我打印出鼠标的坐标,点击按钮后立即更新。

任何人都可以帮助或想到替代结构吗?

import sys
from PyQt4 import QtGui

from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
import matplotlib.pyplot as plt


from matplotlib.patches import Rectangle



class Annotate(object):
    def __init__(self, ax):
        self.ax = ax
        self.rect = Rectangle((0,0), 0, 0)
        self.x0 = None
        self.y0 = None
        self.x1 = None
        self.y1 = None
        self.ax.add_patch(self.rect)
        self.ax.figure.canvas.mpl_connect('button_press_event', self.on_press)
        self.ax.figure.canvas.mpl_connect('button_release_event', self.on_release)
        self.ax.figure.canvas.mpl_connect('motion_notify_event', self.on_motion)

        self.is_pressed = 0

    def on_motion(self, event):
        if self.is_pressed:
            self.x1 = event.xdata
            self.y1 = event.ydata 
            print(self.x1, self.y1)

            self.rect.set_width(self.x1 - self.x0)
            self.rect.set_height(self.y1 - self.y0)
            self.rect.set_xy((self.x0, self.y0))
            self.rect.figure.canvas.draw() 

    def on_press(self, event):
        self.is_pressed = 1
        self.x0 = event.xdata
        self.y0 = event.ydata

    def on_release(self, event):
        self.is_pressed = 0


class Window(QtGui.QDialog):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)
        self.figure = plt.figure(facecolor='white')
        self.canvas = FigureCanvas(self.figure)
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.canvas)
        self.setLayout(layout)

        ''' plot some random stuff '''
        ax = self.figure.add_subplot(111)
        self.ax = ax
        ax.plot()
        self.canvas.draw()

    def get_ax(self):
        return self.ax

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    main = Window()
    ax = main.get_ax()
    main.show()
    a = Annotate(ax)
    sys.exit(app.exec_())

0 个答案:

没有答案