我在我的程序中使用了这个函数:
void delay(QState * state1, int millisecond, QAbstractState * state2)
{
auto timer = new QTimer(state1);
timer->setSingleShot(true);
timer->setInterval(millisecond);
QObject::connect(state1, &QState::entered, timer, static_cast<void (QTimer::*)()>(&QTimer::start));
QObject::connect(state1, &QState::exited, timer, &QTimer::stop);
state1 -> addTransition(timer, SIGNAL(timeout()), state2);
}
我从一个例子中复制粘贴,我不明白这部分代码:
QObject::connect(state1,..., static_cast<void (QTimer::*)()>(&QTimer::start));
任何人都可以向我解释这段代码是什么?它在程序中的工作原理?
PS。我尝试用这个改变代码,但它没有工作:
QTimer *timer = new QTimer(state1);
.
. //same code as before
.
QObject::connect(stato1,&QState::entered,timer,[&] {timer->start();} );
QObject::connect(stato1,&QState::exited, timer,[&] {timer->stop(); } );
stato1 -> addTransition(timer,SIGNAL(timeout()),stato2);
答案 0 :(得分:3)
有两个QTimer::start
slots,一个没有参数,另一个有int msec
参数。要使用新的连接语法连接到正确的连接语法,您必须使用static_cast
指定插槽类型。
所以在这一行:
QObject::connect(state1, &QState::entered, timer, static_cast<void (QTimer::*)()>(&QTimer::start));
您连接到不带参数的QTimer::start
广告位。
如果您的信号带有int
参数且想要连接到QTimer::start(int msec)
广告位,则可以这样做:
connect(this, &MyClass::mySignal, timer, static_cast<void (QTimer::*)(int)>(&QTimer::start));
您可以使用新的连接语法here了解有关使用重载信号/插槽的更多信息。
您还可以使用qOverload
来消除对丑陋static_cast
的需求。
在使用lambda表达式的代码段中,您可以通过引用捕获timer
。您应该通过值来捕获它:
QObject::connect(stato1, &QState::entered, timer, [=]{timer->start();});