2017-09-25 67 views
1

在Qt 5.9中,我试图用C++关键字代替SLOT。这是可能的(没有一个单独的方法)?在连接信号/插槽中使用C++关键字

喜欢的东西:

QObject::connect(&timer, SIGNAL(timeout()), this, (delete image_ptr)); 

这是行不通的,我下面的代码示例:连接样品中

QImage *image_ptr = new QImage(3, 3, QImage::Format_Indexed8); 
QEventLoop evt; 
QFutureWatcher<QString> watcher; 
QTimer timer(this); 
timer.setSingleShot(true); 
QObject::connect(&watcher, &QFutureWatcher<QString>::finished, &evt, &QEventLoop::quit); 
QObject::connect(&timer, SIGNAL(timeout()), &watcher, SLOT(cancel())); 
QObject::connect(&timer, SIGNAL(timeout()), &evt, SLOT(quit)); 
QObject::connect(&timer, SIGNAL(timeout()), this, (delete image_ptr)); 
QFuture<QString> future = QtConcurrent::run(this,&myClass::myMethod,*image_ptr); 
watcher.setFuture(future); 
timer.start(100); 
evt.exec(); 
+3

使用拉姆达。 https://artandlogic.com/2013/09/qt-5-and-c11-lambdas-are-your-friend/ – drescherjm

+1

虽然说这看起来很危险。我的意思是如果并发执行仍在运行,你释放图像坏事会发生.. – drescherjm

回答

1

您可以使用lambda表达式相反(更多关于新的连接语法here)。

考虑到接收器在这些示例中是slot的其他所有者(如果使用旧语法),它不是全局变量或宏。另外,使用lambda表达式时,您无法访问sender()方法,因此您必须通过其他方法处理访问它们。要解决这些情况,你必须在lambda中捕获这些变量。就你而言,它只是指针。

QObject::connect(&timer, &QTimer::timeout, [&image_ptr]() { delete image_ptr; }); 
+0

是的,它按需工作,谢谢! –

3

lambda表达式:

connect(
    sender, &Sender::valueChanged, 
    [=](const QString &newValue) { receiver->updateValue("senderValue", newValue); } 
);