gpt4 book ai didi

c++ - 如何使用带有函数指针的新 QObject::connect 语法将 QSslSocket::error 信号连接到插槽?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:02:02 24 4
gpt4 key购买 nike

我正在尝试编译这段代码。

标题:

#ifndef SOCKETTEST_H
#define SOCKETTEST_H

#include <QObject>
#include <QSslSocket>

class SocketTest : public QObject
{
Q_OBJECT
public:
explicit SocketTest(QObject *parent = 0);

signals:

public slots:
void onError(QAbstractSocket::SocketError socketError);

};

#endif // SOCKETTEST_H

来源:

#include "sockettest.h"

SocketTest::SocketTest(QObject *parent) :
QObject(parent)
{
QSslSocket *socket = new QSslSocket(this);
connect(socket, &QSslSocket::error, this, &SocketTest::onError);
}

但是我收到了这个错误:

sockettest.cpp:7: 错误:没有匹配函数调用 'SocketTest::connect(QSslSocket*&, , SocketTest* const, void (SocketTest::*)(QAbstractSocket::SocketError))'

我想使用 connect() 函数的新语法:

QMetaObject::Connection QObject::connect(const QObject * sender, PointerToMemberFunction signal, const QObject * receiver, PointerToMemberFunction method, Qt::ConnectionType type = Qt::AutoConnection) [static]

所以,我的问题是:如何使用连接函数的新语法将 QSslSocket::error() 信号连接到 SocketTest::onError() 插槽?

最佳答案

问题:这个类中还有一个error()。参见 here ,所以你应该使用特殊技巧:

  QObject::connect(socket, static_cast<void (QSslSocket::*)(QAbstractSocket::SocketError)>(&QAbstractSocket::error), [socket] (QAbstractSocket::SocketError) {
        qDebug()<< "ERROR " << socket->errorString();
        socket->deleteLater();
    });
}

可编译示例:

QSslSocket *socket = new QSslSocket(this);
connect(socket, static_cast<void (QSslSocket::*)(QAbstractSocket::SocketError)>(&QAbstractSocket::error), [socket] (QAbstractSocket::SocketError) {
qDebug()<< "ERROR " << socket->errorString();
socket->deleteLater();
});
socket->connectToHostEncrypted("imap.example.com", 993);

我知道这段代码很丑,但它只是实现你想要的东西的一种方法,当然你也可以使用旧语法。

作为doc说:

Overload

As you might see in the example, connecting to QAbstractSocket::error is not really beautiful since error has an overload, and taking the address of an overloaded function requires explicit casting.

Some macro could help (with c++11 or typeof extensions)

The best thing is probably to recommend not to overload signals or slots …

… but we have been adding overloads in past minor releases of Qt because taking the address of a function was not a use case we support. But now this would be impossible without breaking the source compatibility.

关于c++ - 如何使用带有函数指针的新 QObject::connect 语法将 QSslSocket::error 信号连接到插槽?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27378658/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com