QObject::connect cant connect signal to a slot of *this* object

1k Views Asked by At

The title might be hard to understand, sorry for that.

I have problem connection signal to slot. There are no compile errors, but the connect returns false. There is error line printed in the console:

QObject::connect: No such slot QObject::clientConnected_() in ../server/server.cpp:8

I think the problem is that connect does not see the slot clientConnected_() in the class Server. Or maybe looks for it in class QObject for some reason.

Code is as follows:

server.h

#ifndef SERVER_H
#define SERVER_H

#include <QtNetwork>
#include <QTcpServer>
#include <QObject>

class Server : public QObject
{
    Q_OBJECT
public:
    bool startListening(const quint16 port);
public slots:
    static void clientConnected_();
private:
    QTcpServer * server_;
};

#endif // SERVER_H

server.cpp

#include "server.h"

#include <iostream>

bool Server::startListening(const quint16 port)
{
    server_ = new QTcpServer();
    QObject::connect(server_,SIGNAL(newConnection()),this,SLOT(clientConnected_()));
    return server_->listen(QHostAddress::Any,port);
}

void Server::clientConnected_()
{
    std::cout << "Connection established!" << std::endl;
    return;
}

Any ideas?

2

There are 2 best solutions below

0
Artmetic On

static void clientConnected_();

change to

private slots: void clientConnected_();

0
Arman Oganesyan On

As was mentioned, youd should decalre your 'void clientConnected_()' as a non-static (you can't connect to static member, but if you want you can call static method from your slot). And also you have to declare slots in 'slot' section to make MOC able to parse your slots.

More information you can find here http://doc.qt.io/qt-5/signalsandslots.html