无法识别继承类的插槽

Slot of inherited class not recognized

本文关键字:插槽 继承 识别      更新时间:2023-10-16

我正在尝试实现一个自定义的QTcpSocket类,但似乎在运行时无法识别我的插槽我总是得到:

Object::connect: No such slot QTcpSocket::timeoutSlot()

这是我的代码:

我的标题:

#ifndef CUSTOM_SOCKET_H
#define CUSTOM_SOCKET_H
#include <QTcpSocket>
#include <QTimer>
class CustomSocket : public QTcpSocket {
    Q_OBJECT
public:
    CustomSocket(QObject* = 0);
private:
    QTimer *mAuthTimeout;
public slots:
    void timeoutSlot();
};
#endif

实现:

#include "customSocket.h"
CustomSocket::CustomSocket(QObject *aParent):QTcpSocket(aParent)
{
  mAuthTimeout = new QTimer();
  connect(mAuthTimeout, SIGNAL(timeout()), this, SLOT(timeoutSlot()));
  mAuthTimeout->start(5000);
}
void CustomSocket::timeoutSlot(){
  std::cout << "Timeout " << std::endl;
}
上面

引用的代码没有任何问题。

您收到的警告有 2 件奇怪的事情;

  • 它抱怨QTcpSocket::timeoutSlot()。 我们不是在尝试连接到QTcpSocket,而是连接到CustomSocket。警告应该提到这一点。如果没有,则Q_OBJECT宏可能丢失。
  • 如果我复制/粘贴代码并将其添加到空目录中,请添加main(),然后使用qmake -project; qmake; make。它工作得很好。没有警告。

查看 QTcpSocket 类,它是用Q_DISABLE_COPY宏声明的。这可能会导致您看到的错误。

无论情况是否如此,我认为您最好不要从 QTcpSocket 继承,而是在您的类中创建一个实例:-

class CustomSocket : public QObject
{
    Q_OBJECT
    private:
        QTCPSocket* m_pSocket;    
};

CustomSocket::CustomSocket(QObject* parent)
    :QObject(parent)
{
    m_pSocket = new QTcpSocket(this);
}

然后,您应该可以连接到 QTcpSocket 并使用其信号和插槽正常与其通信。