Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt connect() without QObject or slots

Tags:

c++

qt

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.

like image 935
Krythic Avatar asked Nov 14 '14 19:11

Krythic


People also ask

What is connect function in Qt?

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).

What is signals and slots in Qt?

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.

What is Q_object macro?

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.


2 Answers

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); 
like image 150
dtech Avatar answered Sep 23 '22 20:09

dtech


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();} );
like image 21
Jonathan Mee Avatar answered Sep 25 '22 20:09

Jonathan Mee