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