【问题标题】:Mouse coordinates of pytqt graph linepytqt图形线的鼠标坐标
【发布时间】:2018-11-22 19:00:54
【问题描述】:

每当我将鼠标移到图表顶部时,我都会尝试获取随机函数图的 (x,y) 值。我正在使用 pyqtgraph.SignalProxy 并将其连接到回调 mousedMoved。

我得到这个错误: NameError:未定义全局名称“mouseMoved”

代码如下:

import sys
from pyqtgraph.Qt import QtGui, QtCore
import numpy as np
import pyqtgraph as pg
import time
import random

class TestClass(QtGui.QMainWindow):
  #####################################################
  def __init__(self):
    super(TestClass, self).__init__()
    self.initUI()

  #####################################################
  # GUI construction
  def initUI(self):
    win = pg.GraphicsWindow(title="Mouse Point, x & y")

    # creates plot
    self.plot = pg.PlotWidget()
    self.plot.setLabel('left', "B", units='T')
    self.plot.setLabel('bottom', "t", units='s')
    self.plot.showGrid(x=1, y=1, alpha=None)
    self.setCentralWidget(win)
    self.setGeometry(600, 600, 600, 600)
    self.setWindowTitle('Mouse Point, x& y GUI')

    # Create some widgets to be placed inside
    btnRandon = QtGui.QPushButton('Random Function')


    # Create a grid layout to manage the widgets size and position
    layout = QtGui.QGridLayout()
    win.setLayout(layout)

    # Add widgets to the layout in their proper positions
    layout.addWidget(btnRandon, 0, 0) # button to show or hide the OldB
    layout.addWidget(self.plot, 1, 0)

    mypen = pg.mkPen('y', width=1)
    self.curve = self.plot.plot(pen=mypen)

    # Plot
    self.t_plot_max = 30
    self.fe = 10e3
    self.t = np.arange(-1 * self.t_plot_max, 0, 1.0 / self.fe)
    self.len_signal = len(self.t)
    self.signal = np.zeros(self.len_signal, dtype=np.double)

    # status bar
    self.statusBar()

    # clicked button evt
    btnRandon.clicked.connect(self.buttonRandomClicked)

    # show graph
    self.show()

  #####################################################
  def mouseMoved(evt):
    mousePoint = self.curve.vb.mapSceneToView(evt[0])
    label.setText("<span style='font-size: 14pt; color: white'> x = %0.2f, <span style='color: white'> y = %0.2f</span>" % (mousePoint.x(), mousePoint.y()))


  #####################################################
  def buttonRandomClicked(self):
    print ("Show/Hide OldB")
    self.signal = np.random.rand(20)
    self.curve.setData(self.signal)

#####################################################
  def update(self):
    proxy = pg.SignalProxy(self.curve.scene().sigMouseMoved, rateLimit=60, slot=mouseMoved)
    self.statusBar().showMessage('Update timer event')

# MAIN ##################################################
def main():
  app = QtGui.QApplication(sys.argv)
  ex = TestClass()
  timer = QtCore.QTimer()
  timer.timeout.connect(ex.update)
  timer.start(200)
  sys.exit(app.exec_())


if __name__ == '__main__':
  main()

艾米知道我做错了什么吗?

谢谢。

【问题讨论】:

    标签: python pyqt pyqt4 mouseevent pyqtgraph


    【解决方案1】:

    没有必要使用QTimer 来执行此任务并创建一个名为update() 的方法,因为QMainWindow 具有类似的方法并且可能会干扰正确的操作。

    每次移动鼠标都会发出sigMouseMoved信号,所以一般情况下不需要使用SignalProxy

    信号sigMouseMoved 返回相对于PlotWidget 的像素坐标,而不是绘图坐标,因此必须使用mapSceneToViewmapSceneToView 方法进行转换@--> @ 987654330@ --> PlotWidget.

    最后,不用GraphicsWindow(),这会创建另一个窗口,一个QWidget就够了。

    import sys
    from pyqtgraph.Qt import QtGui, QtCore
    import numpy as np
    import pyqtgraph as pg
    import random
    
    class TestClass(QtGui.QMainWindow):
        #####################################################
        def __init__(self):
            super(TestClass, self).__init__()
            self.initUI()
        ####################################################
        # GUI construction
        def initUI(self):
            self.setWindowTitle("Mouse Point, x & y")
            win = QtGui.QWidget()
            # creates plot
            self.plot = pg.PlotWidget()
            self.plot.setLabel('left', "B", units='T')
            self.plot.setLabel('bottom', "t", units='s')
            self.plot.showGrid(x=1, y=1, alpha=None)
            self.setCentralWidget(win)
            self.setGeometry(600, 600, 600, 600)
            self.setWindowTitle('Mouse Point, x& y GUI')
    
            # Create some widgets to be placed inside
            btnRandon = QtGui.QPushButton('Random Function')
            # Create a grid layout to manage the widgets size and position
            layout = QtGui.QGridLayout(win)
    
            # Add widgets to the layout in their proper positions
            layout.addWidget(btnRandon, 0, 0) # button to show or hide the OldB
            layout.addWidget(self.plot, 1, 0)
    
            mypen = pg.mkPen('y', width=1)
            self.curve = self.plot.plot(x=[], y=[], pen=mypen)
    
            # Plot
            self.t_plot_max = 30
            self.fe = 10e3
            self.t = np.arange(-1 * self.t_plot_max, 0, 1.0 / self.fe)
            self.len_signal = len(self.t)
            self.signal = np.zeros(self.len_signal, dtype=np.double)
    
            btnRandon.clicked.connect(self.buttonRandomClicked)
            self.curve.scene().sigMouseMoved.connect(self.onMouseMoved)
    
        def onMouseMoved(self, point):
            p = self.plot.plotItem.vb.mapSceneToView(point)
            self.statusBar().showMessage("{}-{}".format(p.x(), p.y()))
    
        def buttonRandomClicked(self):
            print ("Show/Hide OldB")
            self.signal = np.random.rand(20)
            self.curve.setData(self.signal)
    
    
    # MAIN ##################################################
    def main():
        app = QtGui.QApplication(sys.argv)
        ex = TestClass()
        ex.show()
        sys.exit(app.exec_())
    
    
    if __name__ == '__main__':
        main()
    

    【讨论】:

    • 嗨。我在这个应用程序中使用了 QTimer.. 是其他东西的一部分,我只是在这里添加了它。非常感谢您的编辑。我让它工作得很好。干杯
    【解决方案2】:

    抱歉,我正在使用 PyQt5。试试看:

    import sys
    
    #from pyqtgraph.Qt import QtGui, QtCore     # ---
    from PyQt5 import QtWidgets, QtGui, QtCore  # +++
    
    import numpy as np
    import pyqtgraph as pg
    import time
    import random
    
    class TestClass(QtGui.QMainWindow):
      #####################################################
      def __init__(self):
        super(TestClass, self).__init__()
        self.num = 0                        ### +++
        self.initUI()
    
      #####################################################
      # GUI construction
      def initUI(self):
        win = pg.GraphicsWindow(title="Mouse Point, x & y")
    
        # creates plot
        self.plot = pg.PlotWidget()
        self.plot.setLabel('left', "B", units='T')
        self.plot.setLabel('bottom', "t", units='s')
        self.plot.showGrid(x=1, y=1, alpha=None)
        self.setCentralWidget(win)
        self.setGeometry(600, 600, 600, 600)
        self.setWindowTitle('Mouse Point, x& y GUI')
    
        # Create some widgets to be placed inside
        btnRandon = QtGui.QPushButton('Random Function')
    
    
        # Create a grid layout to manage the widgets size and position
        layout = QtGui.QGridLayout()
        win.setLayout(layout)
    
        # Add widgets to the layout in their proper positions
        layout.addWidget(btnRandon, 0, 0) # button to show or hide the OldB
        layout.addWidget(self.plot, 1, 0)
    
        mypen = pg.mkPen('y', width=1)
        self.curve = self.plot.plot(pen=mypen)
    
        # Plot
        self.t_plot_max = 30
        self.fe = 10e3
        self.t = np.arange(-1 * self.t_plot_max, 0, 1.0 / self.fe)
        self.len_signal = len(self.t)
        self.signal = np.zeros(self.len_signal, dtype=np.double)
    
        # status bar
        self.statusBar()
    
        # clicked button evt
        btnRandon.clicked.connect(self.buttonRandomClicked)
    
        # show graph
        self.show()
    
    #  ### ------------------------------------------------
    #  def mouseMoved(evt):
    #    mousePoint = self.curve.vb.mapSceneToView(evt[0])
    #    label.setText("<span style='font-size: 14pt; color: white'> x = %0.2f, <span style='color: white'> y = %0.2f</span>" % (mousePoint.x(), mousePoint.y()))
    
    
      #####################################################
      def buttonRandomClicked(self):
        print ("Show/Hide OldB")
        self.signal = np.random.rand(20)
        self.curve.setData(self.signal)
    
    #####################################################
    #  def update(self):
    #    proxy = pg.SignalProxy(self.curve.scene().sigMouseMoved, rateLimit=60, slot=mouseMoved)
    #    self.statusBar().showMessage('Update timer event')
    ### vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
      def update(self):
        ### +++++++++++++++++++++++++++++++++++++++++++++
        def mouseMoved(evt): 
          print("-->> def mouseMoved(evt):", evt)
          print("\tevt.x()=`{}`, evt.y()=`{}`".format(evt.x(), evt.y()))
    
          # AttributeError: 'PlotDataItem' object has no attribute 'vb'        ### ???????
          #mousePoint = self.curve.vb.mapSceneToView(evt[0])
    
          # vvvv - > label what is it? <-- NameError: name `label` is not defined ### ???????
          #label.setText("<span style='font-size: 14pt; color: white'> x = %0.2f, <span style='color: white'> y = %0.2f</span>" % (mousePoint.x(), mousePoint.y()))
    
    
        self.source = self.curve.scene().sigMouseMoved
        #print(" source ", self.source)
        proxy = pg.SignalProxy(self.source, rateLimit=60, slot=mouseMoved) #+self
        #print("def update(self):222", proxy)
        if self.source is None:
            pass
            #sp.connect(sp, QtCore.SIGNAL('signal'), slot)
        else:
            #sp.connect(sp, signal, slot)
            proxy.signal.connect(mouseMoved)
    
        self.statusBar().showMessage('Update timer event `{}`'.format(self.num))
        self.num += 1    
        return proxy    
    
    
    
    # MAIN ##################################################
    def main():
      app = QtGui.QApplication(sys.argv)
      ex = TestClass()
      timer = QtCore.QTimer()
      timer.timeout.connect(ex.update)
      timer.start(200)
      sys.exit(app.exec_())
    
    
    if __name__ == '__main__':
      main()
    

    【讨论】:

    • 不,mouseMoved() 不会被调用。 :/ 它对你有用吗?
    • 对不起,我没有使用 pyqtgraph 模块的经验。但是我从模块mouseMoved (evt) 中得到了值(x,y)。一些错误被注释掉。我认为进一步你会成功。查看更新的代码。
    猜你喜欢
    • 1970-01-01
    • 2018-11-16
    • 2022-09-23
    • 2013-04-30
    • 2012-07-07
    • 2015-07-03
    • 1970-01-01
    • 2021-01-06
    • 1970-01-01
    相关资源
    最近更新 更多