在我用python处理我的ubuntu(14.04)操作系统上的原始鼠标数据的史诗般的努力中,在这里的很多帮助下,我再次陷入困境。我似乎很难理解pyqtgraph的“简便性”。我要做的就是用一个开始/暂停/停止按钮,一个显示数字的列表小部件和一个让我看看正在发生什么的情节将我现在拥有的代码包装到一个漂亮的小gui中。我想我的主要问题是,我不太了解pyqt中的整个事件。
无论如何,以一个具有我想要的小部件的“简单”示例为例,我无法实现我的代码(编辑得更简单):

#!/usr/bin/python
import threading
import struct
import time
import numpy as np

from PyQt4 import QtGui  # (the example applies equally well to PySide)
from PyQt4 import QtCore
import pyqtgraph as pg
##
data =[(0,0)]
sum_data = [(0,0)]
file = open("/dev/input/mouse2", "rb")

def getMouseEvent():
  buf = file.read(3);
  #python 2 & 3 compatibility
  button = buf[0] if isinstance(buf[0], int) else ord(buf[0])
  x,y = struct.unpack( "bb", buf[1:] );
  print x,y
  return x, y

def mouseCollect():
  while True:
   data.append(getMouseEvent())
   sum_data.append(tuple(map(sum,zip(sum_data[-1],data[-1]))))
   plot.plot(sum_data[0], clear=True)
   pg.QtGui.QApplication.processEvents()
   print sum_data[-1]

## Always start by initializing Qt (only once per application)
app = QtGui.QApplication([])

## Define a top-level widget to hold everything
w = QtGui.QWidget()

## Create some widgets to be placed inside
btn1 = QtGui.QPushButton('Start')

listw = QtGui.QListWidget()
plot = pg.PlotWidget()

def start_btn():
  print 'test'
  threading.Thread(target=mouseCollect).start()

btn1.clicked.connect(start_btn)

## Create a grid layout to manage the widgets size and position
layout = QtGui.QGridLayout()
w.setLayout(layout)
## Add widgets to the layout in their proper positions
layout.addWidget(btn1, 0, 0)   # button goes in upper-left
layout.addWidget(plot, 0, 1, 4, 1)
## Display the widget as a new window
w.show()
## Start the Qt event loop
app.exec_()
##------------------------------------------------------------------


当我按下开始按钮时,窗口冻结,什么也没发生。我的想法是,如果我按下按钮,它会连接到那里的methot状态,并且只是在做它的工作。好的,我有一个无限循环,但至少我认为我应该看到一些东西。希望能提供任何帮助,也欢迎您提供有关此事的良好阅读的任何提示。

问候
编辑:根据echocage的建议插入一个线程

最佳答案

重复更新的最佳方法是使用QTimer。这样,您允许程序控制在每次更新后返回Qt事件循环(不允许无限循环),并且Qt会定期为您调用更新函数。

例如,请参见pyqtgraph随附的许多更新绘图示例之一:https://github.com/pyqtgraph/pyqtgraph/blob/develop/examples/Plotting.py#L58

线程很难正确完成,如果做错了,通常会导致崩溃,难以调试。我建议避免使用线程,除非您对事件系统非常有信心并且熟悉线程的陷阱。

关于python - 带有pyqtgraph的Python实时鼠标数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28075205/

10-12 06:18