Qt C++将具有非空签名的信号连接到lambda

Qt C++ connect signal with non-void signature to lambda

本文关键字:信号 连接 lambda C++ Qt      更新时间:2023-10-16

我想将具有非void签名的信号连接到lambda函数。我的代码看起来像下面的

QTimeLine *a = new QTimeLine(DURATION, this); connect(a, &QTimeLine::valueChanged, [a,this](qreal r) mutable { this->setMaximumHeight(r);});

以类似于SIGNAL-SLOT方法的方式:

connect(a, SIGNAL(valueChanged(qreal),this,SLOT(doStuff(qreal)));

我对lambda的连接进行了编译,但它不会更改this->height()。我做错了什么?我应该如何编写lambda,使其从valueChanged获取qreal?我阅读了相关文档,但找不到有用的示例。

****编辑***

事实上,它是有效的,我得到了错误的QTimeLine设置。是的,我不需要捕捉a。我试图为QTableWidget的自定义insertRow()方法设置动画。我还让lambda更改了表行的高度,而不是所包含的小部件的高度。作为参考,以下是工作片段:

QTimeLine *a = new QTimeLine(DURATION,this);
connect(a,&QTimeLine::valueChanged,[this](qreal r) mutable {
     this->list->setRowHeight(0,r * ROW::HEIGHT);
     });
a->start();

无论如何,非常感谢您的快速回复。

应该能正常工作。这是一个完整的SSCCE,证明它的工作。检查你所做的事情在原则上的不同。

main.cpp

#include <QTimeLine>
#include <QObject>
#include <QDebug>
#include <QCoreApplication>
class Foo
{
    void setMaximumHeight(int h) {height = h; qDebug() << "Height:" << height;}
    public:
    void doStuff() { QObject::connect(&timeLine, &QTimeLine::valueChanged, [this](qreal r) mutable { setMaximumHeight(r);}); timeLine.start(); }
    int maximumHeight() const { return height; }
    int height{0};
    int DURATION{100};
    QTimeLine timeLine{DURATION};
};
int main(int argc, char **argv)
{
    QCoreApplication application(argc, argv);
    Foo foo;
    foo.doStuff();
    return application.exec();
}

main.pro

TEMPLATE = app
TARGET = main
QT = core
CONFIG += c++11
SOURCES += main.cpp

构建并运行

qmake && make && ./main