2017-06-22 243 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_()) 
相關問題