Inside the constructor, there is a connection:
connect(&amskspace::on_board_computer_model::self(),
SIGNAL(camera_status_changed(const amskspace::camera_status_t&)),
this,
SLOT(set_camera_status(const amskspace::camera_status_t&)));
And the method:
void camera_model::
set_camera_status(const amskspace::camera_status_t& status) {
disconnect(&amskspace::on_board_computer_model::self(),
SIGNAL(camera_status_changed(const amskspace::camera_status_t&)),
this,
SLOT(set_camera_status(const amskspace::camera_status_t&)));
// do the job
}
And I'd like to disconnect this slot after the first call.
The question is: Is there a way to call the slot only once? Without the explicit disconnection? Like a single shot method? Is it possible?
The core idea is to create a wrapper, a special "connect" which automatically disconnect the signal. This is usefull if you use a lot of "call me once" connections; otherwise I'd advice a Qobject::disconnect at the beginning of the slot.
This implementation works by creating 2 connections: a "normal" one, and one that disconnect & cleanup everything just after.
An implementation (using C++11/Qt 5, ):
Caveats/Things to improve:
QObject::disconnect
, but that would cause a small memory leak)Tested using:
and
Test code output:
Getting rid of C++11/Qt5 (I don't have Qt 4.8/GCC4.4.7, so not tested with those) According to the doc, Qt 4.8 doesn't have a connect to function, so I'm using a wrapper:
(I'm making the
ConnectJanitor
's constructor private because the instance self-destructs (delete this
))and for
weakConnect
:If you need to manually break the connections, I suggest to have weakConnect() returning the ConnectJanitor's pointer.