简体   繁体   中英

PyQt4 multithreading using QThread

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_())

The code as posted doesn't actually run, but with a couple minor changes it runs and works fine. Here is the code with modifications:

from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys
import xml.etree.ElementTree

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.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_())

And here is the output:

$ python test.py 
This message I see.
But this one never.

This is with Python 2.6.6, PyQt4 4.8.3, on Debian Unstable.

Can you try it in your environment and see if my modified example works for you? If so, you are on the road to a solution for your real code. =)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM