I know what I am trying to achieve is possible, because I can do it with a lambda expression and I have done it before (Few months ago I just don't remember the syntax). Basically, I want to connect a function to a timer/button/etc. to facilitate the workings of an event.
Here is my working code:
connect( &renderTimer, &QTimer::timeout, [ = ]() {
onTimerUpdate();
} );
That uses a lambda to connect to the slot. I want to just reference the function itself instead of using a lambda expression. I have tried inserting the method onTimerUpdate()
and &onTimerUpdate
none of which work. I don't want to use QObject
or any of it's pre-generated bullcrap — nor do I want to define slots within my class. I want to, quite simply, connect it directly to my function.
There are sender, signal, slot and type. Documentation gives good explanation: This function overloads connect(). Connects signal from the sender object to this object's method. Equivalent to connect(sender, signal, this, method, type).
In Qt, we have an alternative to the callback technique: We use signals and slots. A signal is emitted when a particular event occurs. Qt's widgets have many predefined signals, but we can always subclass widgets to add our own signals to them. A slot is a function that is called in response to a particular signal.
The Q_OBJECT macro is used to enable meta-object features when declared within a class definition. The Meta-Object Compiler ( moc ) will read the class definitions with the declared Q_OBJECT macro and produce the meta-object code.
This is the format when connecting to a member function:
QObject::connect(&renderTimer, &QTimer::timeout, this, &ArclightGLWidget::onTimerUpdate);
This is the format when connecting to a free funciton (same for lambda)
QObject::connect(&renderTimer, &QTimer::timeout, onTimerUpdate);
And this is the format when connecting to a static member function:
QObject::connect(&renderTimer, &QTimer::timeout, SomeType::onTimerUpdate);
Presumably this call is being made inside the class of which onTimerUpdate
is a method. If so you can call:
connect(&renderTimer, &QTimer::timeout, this, &foo::onTimerUpdate);
This is preferable to the lambda because Qt will manage the connection and you will also be able to call sender()
in the slot
.
However if you are within the class in which onTimerUpdate
is a method you can also use the lambda exactly as you have put in the question:
connect( &renderTimer, &QTimer::timeout, [=](){onTimerUpdate();} );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With