QT Connect插槽/信号无法正常工作

时间:2017-08-30 06:27:15

标签: c++ qt qt-signals slot

我在使用以下代码将信号连接到插槽时遇到问题:

#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);
}

emit client->cliComando("prueba");有效,但真实的&#34;发出&#34;别&#39;吨。 控制台不显示任何连接错误,QDebug文本显示一切正常。 原始代码是从http://www.bogotobogo.com/cplusplus/sockets_server_client_QT.php

复制的

1 个答案:

答案 0 :(得分:0)

我发现了问题,我在连接之前发送了一个信号:

client->SetSocket(handle);

发送信号,然后Im CONNECTing ...现在是:

// 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);

它有效。阅读以下内容后我注意到了它:

<强> 13。将所有连接语句置于可能触发其信号的函数调用之前,以确保在触发信号之前建立连接。例如:

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

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

我在https://samdutton.wordpress.com/2008/10/03/debugging-signals-and-slots-in-qt/

找到了它

无论如何,谢谢你的回答!