PyQtGraph自定义PlotDataItem未接收MousedrageEvents

2024-04-19 16:45:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在设置一个自定义PlotDataItem来接收MousedRageEvents。我已根据我的需要调整了this answer。现在,我只向事件添加了一个简单的setData来检查它是否有效。自定义PlotDataItem如下:

class CustomPlotItem(pg.PlotDataItem):
    def __init__(self, *args, **kargs):
        super().__init__(*args, **kargs)

    def setParentItem(self, parent):
        super().setParentItem(parent)
        self.parentBox = self.parentItem().parentItem()      

    def mouseDragEvent(self, ev):
        if ev.button() != QtCore.Qt.LeftButton:
            ev.ignore()
            return

        if ev.isStart():
            if self.parentBox.curveDragged != None or not self.mouseShape().contains(ev.pos()):
                ev.ignore()
                return
            self.parentBox.curveDragged = self            
        elif ev.isFinish():
            self.parentBox.curveDragged = None
            return
        elif self.parentBox.curveDragged != self:
            ev.ignore()
            return

        self.setData([40,50,60,200],[20,50,80,500])
        ev.accept()

PlotDataItem被添加到一个自定义的ViewBox中,它实现了curveDragged,因此我知道拖动的是哪条曲线(如果有)。为了调试,我还禁用了ViewBox的mouseDragEvents。在

但是,当尝试在ViewBox中拖动该线时,不会发生任何操作。另外,如果我在mouseDragEvent的顶部添加一个异常,则不会发生任何事情。这让我相信mouseDragEvent根本没有被调用。在

Im使用python3.3(Anaconda发行版)和pyqtgraph的开发版本(0.9.9)。在

我希望有人能帮我这个:)。提前谢谢。在


Tags: selfreturnifinitdefargsignoreev
1条回答
网友
1楼 · 发布于 2024-04-19 16:45:23

PlotDataItemPlotCurveItemScatterPlotItem的包装器。因此,它实际上没有任何图形,也没有自己的可点击形状。我会尝试生成PlotCurveItem的子类。如果确实需要使用PlotDataItem,则可以对其进行修改,使其从包裹的曲线继承其形状:

class CustomPlotItem(pg.PlotDataItem):
    def __init__(self, *args, **kargs):
        super().__init__(*args, **kargs)
        # Need to switch off the "has no contents" flag
        self.setFlags(self.flags() & ~self.ItemHasNoContents)

    def mouseDragEvent(self, ev):
        print("drag")
        if ev.button() != QtCore.Qt.LeftButton:
            ev.ignore()
            return

        if ev.isStart():
            print("start")
        elif ev.isFinish():
            print("finish")

    def shape(self):
        # Inherit shape from the curve item
        return self.curve.shape()

    def boundingRect(self):
        # All graphics items require this method (unless they have no contents)
        return self.shape().boundingRect()

    def paint(self, p, *args):
        # All graphics items require this method (unless they have no contents)
        return

    def hoverEvent(self, ev):
        # This is recommended to ensure that the item plays nicely with 
        # other draggable items
        print("hover")
        ev.acceptDrags(QtCore.Qt.LeftButton)

相关问题 更多 >