2

我正在为 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,或者您知道如何修复此错误,请告诉我!

4

2 回答 2

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")
于 2012-12-23T22:00:05.460 回答
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)
于 2012-12-04T21:10:35.917 回答