Qt 错误: QObject::connect() 报错 'errorOccurred' 不是 QTcpSocket 成员
解决 Qt 错误: QObject::connect() 报错 'errorOccurred' 不是 QTcpSocket 成员
在使用 Qt 的 QObject::connect() 函数连接 QTcpSocket 的错误信号时,可能会遇到以下错误:
G:\Qt\Client\Smarthome_Client\procession.cpp:18: error: no member named 'errorOccurred' in 'QTcpSocket'
G:\Qt\Client\Smarthome_Client\procession.cpp:20: error: 'this' cannot be implicitly captured in this context
G:\Qt\Client\Smarthome_Client\procession.cpp:20: error: member reference type 'QTcpSocket *' is a pointer; did you mean to use '->'?
G:\Qt\Client\Smarthome_Client\procession.cpp:18: error: 'errorOccurred' is not a member of 'QTcpSocket'
     QObject::connect(&m_socket, &QTcpSocket::errorOccurred, [](QAbstractSocket::SocketError error){
                                  ^
G:\Qt\Client\Smarthome_Client\procession.cpp:20: error: 'this' was not captured for this lambda function
         QAbstractSocket::SocketError errorCode = m_socket.error();
                                                  ^
G:\Qt\Client\Smarthome_Client\procession.cpp:20: error: invalid use of non-static data member 'Procession::m_socket'
原因:
- 'errorOccurred' 不是 QTcpSocket 成员信号: QTcpSocket 类没有 errorOccurred信号,正确的信号是error信号。
- lambda 表达式访问类成员:  lambda 表达式中使用了类成员 m_socket,需要通过this指针来访问。
解决方法:
将代码修改为以下形式:
QObject::connect(&m_socket, QOverload<QAbstractSocket::SocketError>::of(&QTcpSocket::error), this, [=](QAbstractSocket::SocketError error){
    // 获取错误代码
    QAbstractSocket::SocketError errorCode = m_socket->error();
    // 根据错误代码进行相应处理
    switch (errorCode) {
    case QAbstractSocket::ConnectionRefusedError:
        qDebug() << 'Connection refused';
        break;
    case QAbstractSocket::RemoteHostClosedError:
        qDebug() << 'Remote host closed';
        break;
    // 其他错误处理...
    default:
        qDebug() << 'Unknown error';
        break;
    }
});
说明:
- 使用 QOverload<QAbstractSocket::SocketError>::of(&QTcpSocket::error)来指定error信号的重载版本,因为QTcpSocket::error信号有多个重载版本。
- 使用 this指针来捕获 lambda 表达式中的this,从而访问类成员m_socket。
- 使用 ->操作符访问m_socket的成员函数error(),因为m_socket是一个指针。
通过以上修改,就可以正确连接 QTcpSocket 的错误信号并进行错误处理。
 
原文地址: https://www.cveoy.top/t/topic/qh6v 著作权归作者所有。请勿转载和采集!