简体   繁体   English

使用新的Qt5信号/插槽机制连接QTcpSocket :: error()时编译错误

[英]Compile error when connecting QTcpSocket::error() using the new Qt5 signal/slot mechanism

When I try to connect using the old signal/slot mechanism, it works fine, but it gives me a compile error using the new one: 当我尝试使用旧的信号/插槽机制连接时,它工作正常,但它使用新的一个给我一个编译错误:

// Old mechanism, this works:
connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(onError(QAbstractSocket::SocketError)));
// Compile error when using the template version:
connect(socket, &QTcpSocket::error, this, &MainWindow::onError);

This is the error I get: 这是我得到的错误:

error: no matching function for call to 'MainWindow::connect(QTcpSocket*&, , MainWindow*, void (MainWindow::*)(QAbstractSocket::SocketError))'
         connect(socket, &QTcpSocket::error, this, &MainWindow::onError);
                                                                       ^

My slot function: 我的插槽功能:

class MainWindow : public QMainWindow
{
    Q_OBJECT
private slots:
    void onError(QAbstractSocket::SocketError);

I found a similar thread on Qt forums , and they say it's a bug in Qt but would be fixed by 5.1. 在Qt论坛上找到了一个类似的帖子 ,他们说这是Qt中的一个bug但是会被5.1修复。 My version is 5.4.2, however (using MinGW). 我的版本是5.4.2,但是(使用MinGW)。

So is it a Qt bug for real, or is my syntax wrong? 那么它是真正的Qt错误,还是我的语法错误?

You had the right link to the Qt forums, but read the wrong part. 您有与Qt论坛的正确链接,但阅读错误的部分。 Look for static_cast on this page. 在此页面上查找static_cast。

connect (socket, static_cast<void (QTcpSocket::*)(QAbstractSocket::SocketError)>(&QAbstractSocket::error), this, &MainWindow::onError);

This (not very elegant) cast is necessary because the method name "error" is ambiguous. 这个(不是非常优雅)演员是必要的,因为方法名称“错误”是不明确的。

Your link is wrong, reason is that MOC compiler don't know with one should use. 你的链接是错误的,原因是MOC编译器不知道应该使用哪一个。 If there are 2 same name signals but different params, MOC is confused with one you mean. 如果有2个相同的名称信号但是不同的参数,则MOC与您的意思相混淆。

That why sometimes is better to use 'old' syntax than new one. 这就是为什么有时使用'旧'语法比使用新语法更好。

From doc you can find same function as good example of that: doc您可以找到相同的功能作为其中的好例子:

error() const : SocketError
error(QAbstractSocket::SocketError)

With one MOC should use? 有一个MOC应该使用? :) :)

Edit: I know that one of them is signal, other is normal function, but from MOC point of view, this don't matter, both are 'functions' from C++ point of view. 编辑:我知道其中一个是信号,其他是正常功能,但从MOC的角度来看,这没关系,从C ++的角度来看都是'函数'。 Only difference is 'generate c++ code from MOC' (as signals/slots are 'created by moc compiler') 唯一的区别是'从MOC生成c ++代码'(因为信号/插槽是'由moc编译器'创建的)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM