简体   繁体   中英

QT Connect Slot / Signal not working

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM