【问题标题】:PyQt4 multithreading using QThreadPyQt4 多线程使用 QThread
【发布时间】:2011-08-05 19:09:06
【问题描述】:

QThread 中调用xml.etree.ElementTree.fromstring() 函数时会出现无限阻塞。还有很多其他的调用使 QThread 像multiprocessing.Process() 一样被阻塞。 重要的是要说它是一个纯块,没有异常或中断。

这是代码(稍作修改但与源代码相同):

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

【问题讨论】:

  • 你能发布代码吗?我可以比描述它的英语更好地阅读代码;)
  • 你确定它是阻塞而不是抛出异常吗?
  • @Judge:正如我在第一行所说的,没有例外。

标签: python multithreading pyqt pyqt4 qthread


【解决方案1】:

发布的代码实际上并没有运行,但经过一些小的更改,它可以运行并且运行良好。以下是修改后的代码:

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

这是输出:

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

这是在 Debian Unstable 上使用 Python 2.6.6、PyQt4 4.8.3。

您能否在您的环境中尝试一下,看看我修改后的示例是否适合您?如果是这样,您正在为您的真实代码找到解决方案。 =)

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-02
      • 2015-08-21
      • 2015-07-31
      • 2012-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多