>我在程序中使用了这个函数:
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));
任何人都可以向我解释这个代码是什么?它在程序中是如何工作的?
附言。我试图用这个更改该代码,但它不起作用:
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);
有两个QTimer::start
插槽,一个没有参数,一个有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));
您可以在此处阅读有关使用重载信号/插槽和新连接语法的更多信息。
您还可以使用qOverload
来消除丑陋static_cast
的需求。
在使用 lambda 表达式的代码段中,您可以通过引用捕获timer
。您应该改为按值捕获它:
QObject::connect(stato1, &QState::entered, timer, [=]{timer->start();});