2017-08-30 113 views
0

我无法将信号连接到一个槽下面的代码:QT连接插槽/信号不工作

#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");作品,但真正的“发射”没有。 控制台不显示任何连接错误,并且QDebug文本显示一切正常。 原始代码http://www.bogotobogo.com/cplusplus/sockets_server_client_QT.php

+0

向我们显示您的信号处理代码。 – arrowd

+0

_The emit client-> cliComando(“prueba”);作品_你怎么知道这个?此外,您可以简单地将SIGNAL连接到SIGNAL:_connect(client,SIGNAL(cliComando(const QString&)),this,SIGNAL(servComando(const QString &))); _ – Xplatforms

+0

也用作参数的_“prueba”_显然不是_const QString&_ it取决于使用的编译器和Qt开关使用_QStringLiteral(“prueba”)_并设置SIGNAL/SLOT参数为_const QString_,如果直接向函数体插入参数并且不确定QMeta进程中的实例化参数是否仍然可用且具有值 – Xplatforms

回答

0

被复制,我发现这个问题,林发送信号之前连接:

client->SetSocket(handle); 

发送信号,并在其后林连接...现在是:

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

无论如何,感谢您的回答!