Better_Software_Header_MobileBetter_Software_Header_Web

Find what you need - explore our website and developer resources

Single-Shot Signal/Slot Connections

// Trying to make
// connect(sender, &Sender::signal, receiver, &Receiver::slot)
// behave as single-shot connection

auto singleShot = [receiver, connection](parameters) {
  QObject::disconnect(connection); // WHOPS, we don't have this yet!
  receiver->slot(parameters);
};

connection = connect(sender, &Sender::signal, receiver, std::move(singleShot));
auto connection = std::make_unique<QMetaObject::Connection>();
auto connectionPtr = connection.get();

auto singleShot = [receiver, connection = std::move(connection)](parameters) {
  QObject::disconnect(*connection);
  receiver->slot(parameters);
};

*connectionPtr = connect(sender, &Sender::signal, receiver, std::move(singleShot)));
connect(sender, &Sender::signal,
       receiver, &Receiver::slot,
       static_cast<Qt::ConnectionType>(Qt::SingleShotConnection));
KDToolBox::connectSingleShot(sender, &Sender::signal, receiver, &Receiver::slot);

sender->causeSignalEmission(); // calls the slot, and breaks the connection
sender->causeSignalEmission(); // does NOT call the slot

About KDAB


3 Comments

16 - Apr - 2021

Kelteseth

16 - Apr - 2021

Giuseppe D'Angelo

2 - Dec - 2021

Y Malaika

GiuseppeD'Angelo

Giuseppe D’Angelo

Senior Software Engineer