1. 程式人生 > >QT QTcpServer newConnection 訊號無法觸發 槽

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中。