首页 文章

在派生的QObject构造函数中连接Qt信号和插槽

提问于
浏览
0

我正在编写一个简单的 EchoServer 类,继承自 QTcpServer . 当我在构造函数中连接信号和插槽时,它并不顺利 .

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:
};

应用程序确实侦听端口,并且可以进行telneted . 但控制台显示

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

这似乎是将 this 识别为基类 QTcpServer 指针 .

此外,如果我在代码中留下 Q_OBJECT ,它就不会编译,说

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

他们有关系吗?

2 回答

  • 2

    您需要在代码中保留 Q_OBJECT ,并且需要一个析构函数来与您的类一起使用 .

    您可能需要在代码上运行“Clean Project”来修复该链接器错误 .

    还可以看看Q_OBJECT linker error!

    希望有所帮助 .

  • 0

    phyatt 's answer helps me find the problem. So I'中的链接Q_OBJECT linker error!我自己回答这个问题 .

    问题中的代码完全放在一个 main.cpp 文件中,这会阻止Qt的元处理 . 将类定义放入单独的 hpp 标头并重新编译,问题就消失了 . 我正在使用Visual Studio 2012 Qt 5.0 .

相关问题