Search code examples
c++qtsignals-slots

Connect Qt signal and slot in a derived QObject constructor


I am writing a simple EchoServer class, inheriting from QTcpServer. And when I connect signal and slot in the constructor, it does not go well.

class EchoServer : public QTcpServer {
  //Q_OBJECT
public:
  EchoServer(int listenling_port) {
    this->listen(QHostAddress(), listenling_port);
    connect(this, SIGNAL(newConnection()), this, SLOT(HandleIncomingConnection()));
  }
public slots:
  void HandleIncomingConnection() {
    auto echo_handler = EchoServerHandler(this->nextPendingConnection());
    echo_handler.Echo();
  }
private:
};

The application does listen to the port, and can be telneted. But the console displays

"QObject::connect: No such slot QTcpServer::HandleIncomingConnection()",

which seems it is recognizing this as a base class QTcpServer pointer.

Also if I leave Q_OBJECT in the code, it would not compile, saying

"error LNK2001: unresolved external symbol "public: virtual struct QMetaObject const * __thiscall EchoServer::metaObject(void)const " (?metaObject@EchoServer@@UBEPBUQMetaObject@@XZ)",

are they related?


Solution

  • You need to leave Q_OBJECT in your code, and you need a destructor to go with your class.

    You might need to run "Clean Project" on your code to fix that linker error.

    Also check out Q_OBJECT linker error!

    Hope that helps.