Search code examples
c++qtcompiler-errorsmingwsignals-slots

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. My version is 5.4.2, however (using MinGW).

So is it a Qt bug for real, or is my syntax wrong?


Solution

  • You had the right link to the Qt forums, but read the wrong part. Look for static_cast on this page.

    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.