QT Connect Slot / Signal not working

750 views Asked by At

I am having trouble to connect a Signal to a Slot in the following code:

#include "myserver.h"

MyServer::MyServer(QObject *parent) :
    QTcpServer(parent)
{
}

void MyServer::StartServer()
{
    if(listen(QHostAddress::Any, 45451))
    {
        qDebug() << "Server: started";
        emit servComando("Server: started");
    }
    else
    {
        qDebug() << "Server: not started!";
        emit servComando("Server: not started!");
    }
}

void MyServer::incomingConnection(int handle)
{
    emit servComando("server: incoming connection, make a client...");

    // at the incoming connection, make a client
    MyClient *client = new MyClient(this);
    client->SetSocket(handle);

    //clientes.append(client);
    //clientes << client;

    connect(client, SIGNAL(cliComando(const QString&)),this, SLOT(servProcesarComando(const QString&)));

    // para probar
    emit client->cliComando("prueba");

}

void MyServer::servProcesarComando(const QString& texto)
{
    emit servComando(texto);
}

The emit client->cliComando("prueba"); works, but the real "emits" don't. The console does not show any connection error, and the QDebug texts shows everything works well. Original code was copied from http://www.bogotobogo.com/cplusplus/sockets_server_client_QT.php

1

There are 1 answers

0
Juan Carlos Alvez Balbastro On

I found the problem, Im sending a signal BEFORE connecting:

client->SetSocket(handle);

sends the signal, and Im CONNECTing after it... Now it is:

// at the incoming connection, make a client
MyClient *client = new MyClient(this);

connect(client, SIGNAL(cliComando(const QString&)),this, SLOT(servProcesarComando(const QString&)));

client->SetSocket(handle);

And it works. I noticed it after read the following:

13. Put all connect statements before functions calls that may fire their signals, to ensure that the connections are made before the signals are fired. For example:

_myObj = new MyClass();
connect(_myObj, SIGNAL(somethingHappend()), SLOT(doSomething()));
_myObj->init();

not

_myObj = new MyClass();
_myObj->init();
connect(_myObj, SIGNAL(somethingHappend()), SLOT(doSomething()));

I found it at https://samdutton.wordpress.com/2008/10/03/debugging-signals-and-slots-in-qt/

Anyway, thanks for your answers!