Qt 5中使用lambda表示式連線訊號和槽

鍵盤在跳舞發表於2020-09-29

直接上例子: 

    QProcess* process = new QProcess;
    process->setProgram("cmd");
    QStringList argument;
    argument<<"/c"<< QString::fromStdString(strCmd);
    process->setArguments(argument);
    qDebug() << "argument:" << argument;

    QObject::connect(process, &QProcess::finished),this,[this](int){
        std::cout << "process finished." << std::endl;
    });

 

錯誤提示:

 error: C2664: “QMetaObject::Connection QObject::connect(const QObject *,const char *,const char *,Qt::ConnectionType) const”
: 無法將引數 2 從“overloaded-function”

問題分析:

Q_SIGNALS:
    void started(QPrivateSignal);
#if QT_DEPRECATED_SINCE(5, 13)
    QT_DEPRECATED_X("Use QProcess::finished(int, QProcess::ExitStatus) instead")
    void finished(int exitCode); // ### Qt 6: merge the two signals with a default value
#endif
    void finished(int exitCode, QProcess::ExitStatus exitStatus);


// 以上為原始碼部分,我們可以看到finished訊號是有過載的,存在兩個同名函式

 

解決方法如下:

    QProcess* process = new QProcess;
    process->setProgram("cmd");
    QStringList argument;
    argument<<"/c"<< QString::fromStdString(strCmd);
    process->setArguments(argument);
    qDebug() << "argument:" << argument;

    QObject::connect(process, static_cast<void(QProcess::*)(int)>(&QProcess::finished),this,[this](int){
        std::cout << "process finished." << std::endl;
    });

 

相關文章