Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using any c++ function as a Qt slot

Is there a way to use any C++ function as a Qt slot, without having its class inheriting from QWidget?

like image 449
Roman Rdgz Avatar asked Mar 29 '12 08:03

Roman Rdgz


People also ask

What is Q_OBJECT macro?

QObject is the base class for all Qt classes, Q_OBJECT macro is used to enable meta-object features in classes and finally moc is a preprocessor that changes Q_OBJECT macro instances to C++ source code to enable meta object system mechanism in the class in which it is used.

What is Pyqtsignal?

Each PyQt widget, which is derived from QObject class, is designed to emit 'signal' in response to one or more events. The signal on its own does not perform any action. Instead, it is 'connected' to a 'slot'. The slot can be any callable Python function.

Can slots be virtual in Qt?

Yes, just like regular c++ pure virtual methods. The code generated by MOC does call the pure virtual slots, but that's ok since the base class can't be instantiated anyway... Again, just like regular c++ pure virtual methods, the class cannot be instantiated until the methods are given an implementation.


1 Answers

You cannot in Qt versions < Qt 5.

In order to use signals/slots the meta object compiler has to be invoked. To make this happen your class should meet the following requirements:

  • Inherit from QObject or any other subclass (eg QWidget, QPushButton etc)
  • The Q_OBJECT macro should be defined in the private section of the class in order to enable meta-object features such as slots
  • Use the Qt keywords slots and signals in order to declare which functions should be handles by the meta compiler as slots or signals

For more details check the corresponding documentation pages about the meta-object system and the signals & slots

Also check the QObject documentation:

Notice that the Q_OBJECT macro is mandatory for any object that implements signals, slots or properties. You also need to run the Meta Object Compiler on the source file. We strongly recommend the use of this macro in all subclasses of QObject regardless of whether or not they actually use signals, slots and properties, since failure to do so may lead certain functions to exhibit strange behavior.

Edit: Since Qt 5, functors and lambda expressions can be used as slot. See New Signal Slot Syntax in Qt 5

like image 111
pnezis Avatar answered Sep 23 '22 13:09

pnezis