QThread更新UI状态栏? [英] QThread updating UI statusbar?

查看:266
本文介绍了QThread更新UI状态栏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的pyqt gui,它创建一个qthread来打开文件并读取一些信息.我想更新GUI的状态栏.通常,这是我的功能调用,用于更新状态栏上的消息:

I have a simple pyqt gui which creates a qthread to open a file and read some information. I want to update the statusbar of my gui. Normally, this would be my function call to update a message on the statusbar:

class gui1(QtGui.QMainWindow):

    def __init__(self, parent=None):

        super(gui1, self).__init__(parent)
        self.statusBar().showMessage("hello world")
        ...
        # create thread here
        self.mythread = WorkThread(text)   # create instance and pass some text

        self.mythread.finished.connect(self.threadDone)   # signal emitted on finish of thread
        self.mythread.start()   # begin thread

但是,用于更新线程中状态的调用不起作用.如何从qthread中为GUI更新状态栏?

However, the call to update the status within the thread does't work. How can I update the statusbar for my gui from within the qthread?

class WorkThread(QtCore.QThread):

    def __init__(self,text):  
        self.text = text
        QtCore.QThread.__init__(self)

    def __del__(self):
        self.wait()        

    def run(self):
        self.ui.statusBar().showMessage(status)   # WRONG SELF

        return  # must return, so that Qthread finished signal is emitted

推荐答案

您绝不能尝试从GUI线程外部更新GUI.而是将自定义信号添加到工作线程并将其连接到GUI中的插槽:

You must never attempt to update the GUI from outside the GUI thread. Instead, add a custom signal to the worker thread and connect it to a slot in the GUI:

class WorkThread(QtCore.QThread):
    statusMessage = QtCore.pyqtSignal(object)       
    ...

    def run(self):
        self.statusMessage.emit(self.text)

class gui1(QtGui.QMainWindow):    
    def __init__(self, parent=None):    
        super(gui1, self).__init__(parent)
        self.mythread = WorkThread(text)
        ...
        self.mythread.statusMessage.connect(self.handleStatusMessage)

   @QtCore.pyqtSlot(object)
   def handleStatusMessage(self, message):
       self.ui.statusBar().showMessage(message)

这篇关于QThread更新UI状态栏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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