2016-11-28 186 views
0

我尝试在程序中启动Qthread和另一个线程。代码如下所示。 Qthread必须显示图形。 Qthread单独工作时很好,但是当我尝试运行一个线程或多个Qthread时,它不显示任何内容。使用QThread和线程模块进行Python多线程处理

我的设置:的Ubuntu 16.04.1 LTS,蟒蛇2.7.12

模块:pyqtgraph,时间,numpy的,SYS,穿线

的QThread:plotthread.py

from pyqtgraph.Qt import QtGui, QtCore 
import pyqtgraph as pg 
import numpy as np 
import time 
import sys 
class guiThread(QtCore.QThread): 
    def __init__(self): 
     QtCore.QThread.__init__(self) 
     self.status=True 
     self.range=100 
     self.app = QtGui.QApplication(sys.argv) 
     self.app.aboutToQuit.connect(self.stop) 
     self.win = pg.GraphicsWindow(title="Example") 
     self.win.resize(500,400) 
     pg.setConfigOptions(antialias=True) 
     self.px = self.win.addPlot(title="X plot") 
     self.ckx = self.px.plot(pen='y') 
     self.cdx = self.px.plot(pen='r') 
     self.px.setXRange(0, self.range) 
     self.px.setYRange(-180, 180) 
     self.px.showGrid(x=True, y=True) 
     self.timer = QtCore.QTimer() 
     self.timer.timeout.connect(self.updateplot) 
     self.timer.start(0.001) 
     self.kx=np.zeros(self.range) 
     self.dx=np.zeros(self.range) 

    def updateplot(self): 
     self.ckx.setData(self.kx) 
     self.cdx.setData(self.dx) 

    def append(self,sin): 
     self.kx=np.roll(self.kx,-1) 
     self.kx[-1]=sin[0] 
     self.dx=np.roll(self.dx,-1) 
     self.dx[-1]=int(sin[1]) 
    def stop(self): 
     print "Exit" #exit when window closed 
     self.status=False 
     sys.exit() 
    def run(self): 
     print "run" #Qthread run 
     while self.status: 
      sin=np.random.randint(-180,180,2) 
      self.append(sin) #append random number for plot 
      time.sleep(0.01) 

Python Threading:ptiming.py

import time 
import threading 

class timeThread (threading.Thread): 
    def __init__(self,name): 
     threading.Thread.__init__(self) 
     self.name=name 
     self.t=time.time() 
     self.elapsed=0 
    def run(self): 
     print "thread start" 
     while (1): 
      self.elapsed=time.time()-self.t 
      print self.name, self.elapsed 

主营:main.py

import ptiming 
import plotthread 
t1=plotthread.guiThread() 
t1.start() 
t2=ptiming.timeThread("t1") 
t2.start() 
+0

您是否尝试在'guiThread'构造函数中添加'win.show()'? – mguijarr

+2

您不能在单独的线程中执行任何类型的GUI操作。所有gui操作**必须在主线程中发生。 – ekhumoro

+0

@mguijarr是的,我在初始化和plotthread运行功能 – acs

回答

1

在你timeThread类中,.run()方法做一个繁忙的循环:它不断地显示经过的时间,没有任何停顿所以CPU都疯了,我猜OS那么不调度另一个线程。

在这个循环中做一个time.sleep() - 应该恢复正常。

方面评论:你为什么要在guiThread类的构造函数中创建UI元素?使用Qt,无论如何,所有UI元素都属于主线程。正如@ekhumoro所说,GUI操作必须在主线程中发生,这是你的代码中的情况,尽管它是以令人困惑的方式编写的。就我个人而言,我会在主线程中创建明显的UI元素,并添加一个数据处理线程。