matplotlib PyQt4“mpl_connect”构造不能通过类工作

pdtvr36n  于 2023-03-03  发布在  其他
关注(0)|答案(2)|浏览(155)

我是这个stackoverflow社区的新用户。几天来,我一直在为代码中的一些问题而挣扎,这些问题我无法真正弄清楚。在下面的代码中,我试图为我的GUI定义一个自定义选择器工具。我重现了这个“bug”和我程序的主要结构。我试图用“mpl_connect”结构体连接matplotlib信号,但不幸的是,按钮点击的信号,released和mouse motion以及相关的方法对于canvas类似乎是不活动的。下面是不工作的代码。

import sys
    from PyQt4 import QtGui,QtCore
    from matplotlib.figure import Figure
    from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
    from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar

    class Example(QtGui.QMainWindow):
        def __init__(self, parent=None):
            super(Example, self).__init__(parent)
            self.setupUi(self)

        def setupUi(self,parent):
            self.canvas=MyCanvas(self)
            self.toolbar=MyToolBar(self.canvas,self)
            self.addToolBar(QtCore.Qt.BottomToolBarArea,parent.toolbar)

    class MyCanvas(FigureCanvas):
        def __init__(self,parent):
            self.fig=Figure() 
            FigureCanvas.__init__(self, self.fig)
            FigureCanvas.setSizePolicy(self,
                                   QtGui.QSizePolicy.Expanding,
                                   QtGui.QSizePolicy.Expanding)
            self.setParent(parent)

    class MyToolBar(QtGui.QToolBar):
        def __init__(self,canvas,parent):
            super(MyToolBar,self).__init__(parent)
            #
            self.PICK_act=QtGui.QAction("PUSH ME!!",parent,checkable=True)
            self.PICK_act.toggled.connect(lambda: self.pickData(canvas))
            #
            self.addAction(self.PICK_act)
            self.addSeparator()
            ## Creating the matplotlib toolbar
            self.mpl_tool=NavigationToolbar(canvas,parent)
            ## Merge the two toolbar 
            self.addWidget(self.mpl_tool)

        def pickData(self,canvas):
            P=Picker(canvas)     
            if self.PICK_act.isChecked():
                print "CHECKED"
                P._activation(True)
            else:
                print "NOT CHECKED" 
                P._activation(False)
                
    class Picker(object):
        def __init__(self,canvas):
            self.index=None
            self.is_pressed=None     
            # To define the event of PickData_ACTION
            self.canvas=canvas 
            ###
            self.selPressEvent=None      
            self.selReleaseEvent=None
            self.selMoveEvent=None           
        
        def _activation(self,condition):
            if condition==True:
                self.selPressEvent=self.canvas.mpl_connect('button_press_event',self.onpress)
                self.selReleaseEvent=self.canvas.mpl_connect('button_release_event',self.onrelease)
                self.selMoveEvent=self.canvas.mpl_connect('motion_notify_event',self.onmotion)
                print "Picker ON"
                return True
            else:
                self.canvas.mpl_disconnect(self.selPressEvent)
                self.canvas.mpl_disconnect(self.selReleaseEvent)
                self.canvas.mpl_disconnect(self.selMoveEvent)
                print "Picker OFF"
                return False

        def onpress(self,event):
            print "..clicked"
            self.x0 = event.xdata
            self.y0 = event.ydata
            self.is_pressed=True
                
        def onrelease(self,event):
            print "...released"
            self.x1 = event.xdata
            self.y1 = event.ydata
            self.is_pressed=False

        def onmotion(self,event):
            if self.is_pressed==True:
                print "moving"
            
    # =========================================================================        
    def run():
        App=QtGui.QApplication(sys.argv)
        GUI=Example()
        GUI.show()
        sys.exit(App.exec_())
    #
    run()

如果我在“MyCanvas”类中定义相同的方法,它们就可以工作。工作代码如下:

import sys
    from PyQt4 import QtGui,QtCore
    from matplotlib.figure import Figure
    from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
    from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar

    class Example(QtGui.QMainWindow):
        def __init__(self, parent=None):
            super(Example, self).__init__(parent)
            self.setupUi(self)

        def setupUi(self,parent):
            self.canvas=MyCanvas(self)
            self.toolbar=MyToolBar(self.canvas,self)
            self.addToolBar(QtCore.Qt.BottomToolBarArea,parent.toolbar)

    class MyCanvas(FigureCanvas):
        def __init__(self,parent):
            self.fig=Figure() 
            FigureCanvas.__init__(self, self.fig)
            FigureCanvas.setSizePolicy(self,
                                   QtGui.QSizePolicy.Expanding,
                                   QtGui.QSizePolicy.Expanding)
            self.setParent(parent)
            ###
            self.selPressEvent=None      
            self.selReleaseEvent=None
            self.selMoveEvent=None          

        def onpress(self,event):
            print "MyCanvas::onpress ---> clicked"
            
        def onrelease(self,event):
            print "MyCanvas::onrelease ---> release"

        def onmotion(self,event):
            print "MyCanvas::onmotion ---> motion"                
            
    class MyToolBar(QtGui.QToolBar):
        def __init__(self,canvas,parent):
            super(MyToolBar,self).__init__(parent)
            #
            self.PICK_act=QtGui.QAction("PUSH ME!!",parent,checkable=True)
            self.PICK_act.toggled.connect(lambda: self.pickData(canvas))
            #
            self.addAction(self.PICK_act)
            self.addSeparator()
            ## Creating the matplotlib toolbar
            self.mpl_tool=NavigationToolbar(canvas,parent)
            ## Merge the two toolbar 
            self.addWidget(self.mpl_tool)

        def pickData(self,canvas):
            P=Picker(canvas)     
            if self.PICK_act.isChecked():
                print "CHECKED"
                P._activation(True)
            else:
                print "NOT CHECKED" 
                P._activation(False)
                
    class Picker(object):
        def __init__(self,canvas):
            self.index=None
            self.is_pressed=None     
            # To define the event of PickData_ACTION
            self.canvas=canvas
           
        
        def _activation(self,condition):
            if condition==True:
                self.canvas.selPressEvent=self.canvas.mpl_connect('button_press_event',self.canvas.onpress)
                self.canvas.selReleaseEvent=self.canvas.mpl_connect('button_release_event',self.canvas.onrelease)
                self.canvas.selMoveEvent=self.canvas.mpl_connect('motion_notify_event',self.canvas.onmotion)
                print "Picker ON"
                return True
            else:
                self.canvas.mpl_disconnect(self.canvas.selPressEvent)
                self.canvas.mpl_disconnect(self.canvas.selReleaseEvent)
                self.canvas.mpl_disconnect(self.canvas.selMoveEvent)
                print "Picker OFF"
                return False

        def onpress(self,event):
            print "..clicked"
            self.x0 = event.xdata
            self.y0 = event.ydata
            self.is_pressed=True
                
        def onrelease(self,event):
            print "...released"
            self.x1 = event.xdata
            self.y1 = event.ydata
            self.is_pressed=False

        def onmotion(self,event):
            if self.is_pressed==True:
                print "moving"
            
    # =========================================================================        
    def run():
        App=QtGui.QApplication(sys.argv)
        GUI=Example()
        GUI.show()
        sys.exit(App.exec_())
    #
    run()

为了清晰起见,我需要将“Picker”和相关方法与“MyCanvas”类分开,但我真的不明白我的第一段代码中哪里出错了:这个信号似乎被发出了但是没有被接收到。STDERR中没有报告错误。我想我已经正确地考虑了类/方法的作用域。

e7arh2l6

e7arh2l61#

问题在于,mpl回调注册表只保存对它所处理的回调的弱引用(逻辑是如果你不小心保留你从mpl_connect得到的令牌,你可能最终得到你无法得到引用的对象,但是永远不会被gc'd,因为mpl持有一个硬引用)。因此,所发生的事情是,您将Picker对象中的一个方法连接到回调系统,它将超出作用域,得到gc'd,然后当mpl开始运行回调时,它发现对象消失了,并自动删除失效的函数。
您所要做的就是在工具栏类中保留对Picker对象的引用。
这可能应该在上游进行更明确的记录。

6ie5vjzr

6ie5vjzr2#

我在MyToolbar类中解决了初始化选取器的问题:

self.Picker=Picker(canvas)

def pickData(self,canvas):    
    if self.PICK_act.isChecked():
        print "CHECKED"
        self.Picker._activation(True)
    else:
        print "NOT CHECKED" 
        self.Picker._activation(False)

这个答案是由CC BY-SA 3.0下的OP Mat作为问题PyQt 4“mpl_connect”构造不通过类工作的edit发布的。

相关问题