QT QTcpServer newConnection 信号无法触发 槽

最开始我从QTcpServer继承一个类,然后在类的实现中,在listen之后绑定信号和槽。

listen(QHostAddress::AnyIPv4, SERVER_PORT);

connect(this, SIGNAL(QTcpServer::newConnection()), this, SLOT(onNewConnection()));

当客户端使用QTcpSocket  connectToHost(QHostAddress("127.0.0.1"), SERVER_PORT);连接后,客户端显示连接成功了,但是server无法进入onNewConnection()。

网上有一方法:参考

void CServerThread::run() {
   server = new MyServer(host,port);
   exec(); // Start event loop
}
于是我尝试在要使用Server的地方直接用QTcpServer
m_server = new QTcpServer();
m_server->listen(QHostAddress::AnyIPv4, SERVER_PORT);
connect(m_server, SIGNAL(newConnection()), this, SLOT(onNewConnection()));

居然就可以了。(上述的onNewConnection()是定义的slots)

更进一步,那现在直接使用QTcpServer是可以的,那我把QTcpServer换成我的子类(MyServer)不就好了吗?

果不其然:

在Myserver的成员函数进行listen之后,在外部的类(即使用Myserver的类)中进行connect:

Myserver* m_server = new MyServer();

connect(m_server, SIGNAL(newConnection()), this, SLOT(onNewConnection()));

这样也是可以的。

总结:进行connect时,需要在使用对象的地方把对象的信号绑定到当前环境中的slots中。


猜你喜欢

转载自blog.csdn.net/u200814342A/article/details/79242445