2017-06-22 246 views
0

以下代码仅用于测试pyqtgraph的速度。我期望的是永远得到交替图。但是,在执行此代码后,小部件中没有显示任何内容。问题是什么?为什么pyqtgraph这个简单的例子不起作用?

import sys 
from PyQt5.QtWidgets import * 
from PyQt5.QtCore import * 
from random import randint, uniform 
from math import * 
import pyqtgraph as pg 
import time 

class Example(QWidget): 

    def __init__(self): 
     super().__init__() 
     self.x=pg.PlotWidget(self) 
     self.x.setMinimumHeight(400) 
     self.x.setMinimumWidth(400) 
     self.setWindowState(Qt.WindowMaximized) 
     self.u=[i+uniform(1,30) for i in range(1000)] 
     self.v=[-i+uniform(1,30) for i in range(1000)] 
     self.show() 

    def Run(self): 
     while 1: 
      self.x.clear() 
      self.x.plot(self.u) 
      self.x.clear() 
      self.x.plot(self.v) 

app=QApplication(sys.argv) 
ex=Example() 
ex.Run() 
sys.exit(app.exec_()) 

回答

0

在GUI中使用while循环通常是一个坏主意。问题在于它妨碍了GUI保持响应并处理所有GUI事件。

一个选项是使用定时器,例如,一个简单的QTimer。为了在两个不同的数据集之间切换来绘制,你还需要引入一些机制来显示哪一个。

import sys 
#from PyQt5.QtWidgets import * 
#from PyQt5.QtCore import * 
from PyQt4 import QtGui, QtCore 
from random import randint, uniform 
import pyqtgraph as pg 

class Example(QtGui.QWidget): 

    def __init__(self): 
     QtGui.QWidget.__init__(self) 
     self.x=pg.PlotWidget(self) 
     self.x.setMinimumHeight(400) 
     self.x.setMinimumWidth(400) 
     self.setWindowState(QtCore.Qt.WindowMaximized) 
     self.u=[i+uniform(1,30) for i in range(1000)] 
     self.v=[-i+uniform(1,30) for i in range(1000)] 
     self.switch = True 
     self.show() 

    def start(self): 
     self.timer = QtCore.QTimer(self) 
     self.timer.timeout.connect(self.run) 
     self.timer.start(500) 

    def run(self): 
     if self.switch: 
      self.x.clear() 
      self.x.plot(self.u) 
     else: 
      self.x.clear() 
      self.x.plot(self.v) 
     self.switch = not self.switch 

app=QtGui.QApplication(sys.argv) 
ex=Example() 
ex.start() 
sys.exit(app.exec_()) 
相关问题