无法在qt中接收信号

时间:2018-06-06 00:10:25

标签: c++ qt signals signals-slots

我已将类客户端的插槽连接到ClientNetwork类的信号,但它无法正常工作

客户端类:

Client::Client(QString &ip, quint16 port)
{
    clientNetwork = new ClientNetwork(ip,port);
    connect(clientNetwork, &ClientNetwork::clientConnected, this, &Client::connected); 
}
void Client::connected()
{
    qDebug()<<"clientConnected signal received"; //This qDebug is not showing
}

和ClientNetwork类:

ClientNetwork::ClientNetwork(QString &hostIp, quint16 hostPort)
    : port(hostPort), ip(hostIp)
{
    ................
    ...code.........
    ................

    emit clientConnected(); // emit signal
    qDebug()<<"Client::clientConnected"; // this qDebug is showing
}

为什么它无法接收信号?

2 个答案:

答案 0 :(得分:0)

当调用class Client的构造函数时,它首先创建一个ClientNetwork,您已经在其中发出信号clientConnected,然后才会ClientNetwork::ClientConnectedClient::connected之间的连接clientConnected()已成立。

基本上问题是,当信号发出时,信号和插槽之间建立了无连接

如果Client是公开信号,那么您可以在构造函数Client::Client(QString &ip, quint16 port) { clientNetwork = new ClientNetwork(ip,port); connect(clientNetwork, &ClientNetwork::clientConnected, this, &Client::connected); emit clientNetwork->clientConnected(); //or call a public method of Client which does that for you depending on your design. } 中执行以下操作:

{{1}}

答案 1 :(得分:0)

在将Client连接到ClientNetwork之前,您正在发出信号clientConnected()。 您可以通过在发出任何clientConnected()信号之前在ClientNetwork Construct上建立连接并通过将客户端指针或引用传递给ClientNetwork构造函数来解决此问题,但我不建议这样做。

最好的方法是从构造函数中删除所有连接处理,并在ClientNetwork类中创建一个“连接”方法,在Client类上连接信号/插槽后将调用它:

Client::Client(QString &ip, quint16 port)
{
  clientNetwork = new ClientNetwork(ip,port);
  connect(clientNetwork, &ClientNetwork::clientConnected, this, &Client::connected); 
  clientNetwork->connect();
}