Search code examples
qt5overloadingsignals-slotsstatic-cast

qt5: connect overload signal and slot function with static_cast


My environment: Qt5.5 + QtCreator3.5 + OSX10.11

I know that the syntax is different on function connect in qt5 and qt4, and look up the Document to figure out how to use connect() in qt5 to deal with overloading signal/slot function.

I do as suggest, but it still don't work.

newspaper.h

signals:
    // overload function
    void newPaper(const QString &name) const;
    void newPaper(const QString &name, const QDate &date) const;

reader.h

//overload function
void receiveNewspaper(const QString &name) const
{
    qDebug() << "overload(name): Receives Newspaper: " << name;
}
//overload function
void receiveNewspaper(const QString &name, const QDate &date) const
{
    qDebug() << "overload(name, date): Receives Newspaper: " << name << "\tDate:" << date;
}

main.cpp

//connect for overload signal,slot function
QObject::connect(&newspaper,
                 static_cast<void (Newspaper:: *)(const QString &)>(&Newspaper::newPaper),
                 &reader,
                 static_cast<void (Reader:: *)(const QString &)>(&Reader::receiveNewspaper) );

But it get error as follows

./2_16_SignalSlotDeep/main.cpp:16:22: error: address of overloaded function 'newPaper' cannot be static_cast to type 'void (Newspaper::*)(const QString &)'
                     static_cast<void (Newspaper::*)(const QString &)>(&Newspaper::newPaper),
                     ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
../2_16_SignalSlotDeep/newspaper.h:28:10: note: candidate function
    void newPaper(const QString &name) const;
         ^
../2_16_SignalSlotDeep/newspaper.h:29:10: note: candidate function
    void newPaper(const QString &name, const QDate &date) const;
         ^
../2_16_SignalSlotDeep/main.cpp:18:22: error: address of overloaded function 'receiveNewspaper' cannot be static_cast to type 'void (Reader::*)(const QString &)'
                     static_cast<void (Reader::*)(const QString &)>(&Reader::receiveNewspaper) );
                     ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
../2_16_SignalSlotDeep/reader.h:16:10: note: candidate function
    void receiveNewspaper(const QString &name) const
         ^
../2_16_SignalSlotDeep/reader.h:21:10: note: candidate function
    void receiveNewspaper(const QString &name, const QDate &date) const

I already searched the other questions which are not helpful to me. How to fix it? Your advice will be appreciated.

other question link1

other question link2


Solution

  • You can not cast away the "const" of your signals using static_cast. Try removing the "const" behind your signals.

    Normally signals do not need to be const because they are emitted in non-const methods usually.