使用QThread的PyQt4多线程 [英] PyQt4 multithreading using QThread

查看:425
本文介绍了使用QThread的PyQt4多线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

QThread中调用xml.etree.ElementTree.fromstring()函数时,存在无限循环.同样,许多其他调用使QThread像multiprocessing.Process()一样被阻塞. 重要的是要说它是一个纯块,没有例外或中断.

There is an endless block when xml.etree.ElementTree.fromstring() function is called in the QThread. Also lots of other calls makes the QThread blocked like multiprocessing.Process(). Important to say that it is a pure block, no exception or break.

下面是代码(稍作修改,但原理与源代码相同):

Here is the code (a little edited but same principle as the source):

from PyQt4.QtGui import *
from Ui_mainwindow import Ui_MainWindow
import sys
import xml.etree

class Bruton(QThread):
    def __init__(self, mw):
        super(Bruton, self).__init__(mw) 
        self.mw = mw

    def run(self):
        print("This message I see.")
        tree = xml.etree.ElementTree.fromstring("<element>text</element>")
        print("But this one never.")

class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.init_bruton()

    # When the form is shown...
    def showEvent(self, arg1):
        self.bruton.start()

    def init_bruton(self):
        self.bruton = Bruton(self)

app = QApplication(sys.argv)
mw = MainWindow()
mw.show()
sys.exit(app.exec_())

推荐答案

此处显示的代码已缩短(源代码分为两个文件和__ini__.py).我注意到主模块必须是启动QApplication的模块.所以我在程序的主要模块__init__.py中添加了app.exec_().

The code I've shown here is shortened (the source is divided to two files and __ini__.py). I noticed that the main module must be the module that starts the QApplication. So I added app.exec_() to the __init__.py which is the main module of my program.

这篇关于使用QThread的PyQt4多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆