在连接中使用 C++ 关键字 signal/slot
Using C++ keywords in connect signal/slot
在 Qt 5.9 中,我尝试使用 C++ 关键字代替 SLOT。这可能吗(没有单独的方法)?
类似于:
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();
连接示例中的 lambda 表达式:
connect(
sender, &Sender::valueChanged,
[=]( const QString &newValue ) { receiver->updateValue( "senderValue", newValue ); }
);
您可以改用 lambda 表达式(有关新连接语法的更多信息 here)。
考虑到这些示例中的 receiver 是插槽的所有者(如果使用旧语法),它不是全局变量或宏。此外,在使用 lambda 时,您无权访问 sender()
方法,因此您必须注意通过其他方法访问它们。要解决这些情况,您必须在 lambda 中捕获这些变量。在你的例子中,它只是指针。
QObject::connect(&timer, &QTimer::timeout, [&image_ptr]() { delete image_ptr; });
在 Qt 5.9 中,我尝试使用 C++ 关键字代替 SLOT。这可能吗(没有单独的方法)?
类似于:
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();
连接示例中的 lambda 表达式:
connect(
sender, &Sender::valueChanged,
[=]( const QString &newValue ) { receiver->updateValue( "senderValue", newValue ); }
);
您可以改用 lambda 表达式(有关新连接语法的更多信息 here)。
考虑到这些示例中的 receiver 是插槽的所有者(如果使用旧语法),它不是全局变量或宏。此外,在使用 lambda 时,您无权访问 sender()
方法,因此您必须注意通过其他方法访问它们。要解决这些情况,您必须在 lambda 中捕获这些变量。在你的例子中,它只是指针。
QObject::connect(&timer, &QTimer::timeout, [&image_ptr]() { delete image_ptr; });