Qt:从另一个类和线程更新UI(带信号)

时间:2012-12-04 20:54:40

标签: python multithreading qt pyqt pyqt4

我正在为TCP服务器开发一个简单的UI,并且需要使用从服务器发送的日志消息来更新UI,但问题是与该服务器的任何连接都在一个单独的线程中,所以我不能直接触摸UI的小部件(因为它们不是可重入的)。

我已经阅读了一些关于这个主题的文章,并选择了最优雅(也很简单)的方式:信号。

我做了以下事情:

class Ui_Dialog(QtCore.QObject):

    def __init__(self):
        super(QtCore.QObject, self).__init__()

    def setupUi(self, Dialog):        
        Dialog.setObjectName(_fromUtf8("Dialog"))
        Dialog.resize(800, 580)
        self.serverLog = QtGui.QTextEdit(Dialog)
        self.serverLog.setGeometry(QtCore.QRect(0, 0, 800, 480))
        self.serverLog.setObjectName(_fromUtf8("serverLog"))
        #OTHER WIDGETS AND CODE DEFINED HERE

        self.server = None

        #SIGNALS
        self.clearLogButton.clicked.connect(self.serverLog.clear)
        self.stopButton.clicked.connect(self.connectServer)
        self.startButton.clicked.connect(self.connectServer)

    def connectServer(self):
        if (self.server is None):

            host = str(self.ipEdit.text())
            port = int(self.portEdit.text())

            try:
                self.server = server.MainServer((host, port), server.MyHTTPHandler)
                self.server.setup(self)

                self.printLog( "Hooray ! Server connected at {}:{}".format(host, port) )

                # Start a thread with the server -- that thread will then start one more thread for each request
                MainServer_thread = threading.Thread(target=self.server.serve_forever)
                MainServer_thread.daemon = True
                self.server.trigger.connect(QtCore.QObject(self.printLog))
                MainServer_thread.start()         

                self.server.trigger.connect(self.printLog)

            except errno.EADDRINUSE:
                self.printLog("#ERROR: Address already in use. Try a different port.")
            except errno.EADDRNOTAVAIL:
                self.printLog("#ERROR: Address not available.")


    def printLog(self, string):
        self.serverLog.append(_fromUtf8(string))

在服务器类中:

class MainServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
    trigger = QtCore.pyqtSignal(str)

    def printLog(self, message):
        print message
        self.trigger.emit(message)

但是当我运行我的应用程序时,我收到此消息错误:

TypeError: pyqtSignal must be bound to a QObject, not 'instance'

如果还有其他(简单)方法从另一个线程(和类)更新UI,或者您知道如何解决此错误,请告诉我们!

2 个答案:

答案 0 :(得分:3)

这就是这个:

class Signals(QObject):
    trigger = pyqtSignal(str)

MainServer中使用它们:

class MainServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
   def __init__(self, parent=None):
       self.signals = Signals()
       self.signals.trigger.emit("triggered")

答案 1 :(得分:1)

使用我的服务器类中包含的中型对象(类QObject)解决它:

class Logger(QtCore.QObject):

    trigger = QtCore.pyqtSignal(str)
    def __init__(self):
        super(Logger,self).__init__()
    def send(self, string):
        self.trigger.emit(string)