PyQt5:为什么 self.sender() returns 发送它的是基础对象而不是派生对象

PyQt5: Why self.sender() returns the base object not the derived one sent it

我正在用 PyQt5 套接字编写 server/client 代码,我遇到了一个奇怪的行为 首先,我从 QTCPSocket 派生了一个 class,这样我就可以将套接字的用法抽象到我的数据帧中,在发送数据之前使用加密等 所以,让这个 class = mySocket 这是从 QTCPSocket

继承的 class

mySocket 在其 init 中有一些变量,例如:self.key。正如我在所有套接字中所做的那样,我将其 readyread 信号连接到我的名称槽:rxdata

现在,问题来了。 在 rxdata 中,当我尝试获取发送者对象(使用 self.sender() )时,它 returns 是什么QTCPSocket 类型的对象不是我期望的 mySocket 对象。我不明白

我尝试转换使用 qtcpsocketObj 返回的 QTCPsocket。class =mySocket 但是现在的问题是 mySocket.init() 显然没有被调用,所以像 self.key 这样的变量不会被定义。

我该怎么做才能克服这个问题?

经过大量的搜索和调试,

问题不是来自 self.sender()。问题是 QTCPServer 对象 returns QTCPSocket,并像我那样使用 _ class _() 进行转换不是正确的方法。

解决方案是从 QTCPServer 派生一个 class 而不是使它成为 return QTCPSocket,它将 return mySocket class 对象(细节解释得很好在文档中) 这是一个示例代码:

class myQTCPServer(QTcpServer):
     def __init__(self,parent=None):
         super(myQTCPServer, self).__init__(parent)

def incomingConnection(self,socketDescriptor):
        newSock = mySocket(self) 
        newSock.setSocketDescriptor(socketDescriptor)
        self.addPendingConnection(newSock)