15

How do signals and slots work at a high level abstraction?

How are signals and slots implemented at a high level abstraction?

Thomi
  • 11,647
  • 13
  • 72
  • 110
Trevor Boyd Smith
  • 18,164
  • 32
  • 127
  • 177

4 Answers4

15

I've actually read this Qt page about it, and it does a good job of explaining:

https://doc.qt.io/qt-5/signalsandslots.html

Will Da Silva
  • 6,386
  • 2
  • 27
  • 52
Neil
  • 24,551
  • 15
  • 60
  • 81
11

As other people said, there's very good Qt documetnation available for this topic. If you want to know what happens under the hood, this info might help you:

Slots are just regular methods. Nothing special there, EXCEPT moc will save their signature in a table in the intermediate .moc file - you can see this table quite clearly when you look through this file.

This table allows you to call a method using it's signature. The SLOT(mySlot(int)) macro boils down to a string representation of the method in question. There are several ways you can do this, see the documentation for QMetaObject for example.

When a you connect a signal to a slot, the signal and slot signatures are stored for later use. When a signal is emitted, all the slots previously connected to that signal are called using the method described above.

If you want to know more, I suggest looking through the moc-generated code, and stepping through a signal emission and the internals of the connect() call. There's no magic here, but there is a lot of cleverness.

Thomi
  • 11,647
  • 13
  • 72
  • 110
  • 1
    lot of cleverness, but no magic! reminds me of http://catb.org/esr/jargon/html/magic-story.html – jrharshath Sep 24 '09 at 14:24
  • And there are 2 types of connection there. First one: slots are called at the time signal was emitted. And the second one: slots calls are placed in event loop queue. You can manually select the method in connect, but connecting signal and slots from different threads are always queued. – JustAnotherCurious Apr 30 '13 at 11:01
5

We somewhat answered it in your other question

Why does Qt use its own make tool, qmake?

But to go into somewhat more detail, the MOC parses your file looking for signal/slot declarations (as well as properties and the other supported constructs) and generates intermediate code files based on those. These intermediate code files provide strongly-typed access to the signals and slots for the library to use to communicate with your objects.

qmake generates a makefile that automatically includes these intermediate files (as well as any UI or resource files generated) as well as your own code so you can build with your tool chain of choice.

Community
  • 1
  • 1
Ron Warholic
  • 9,994
  • 31
  • 47
4

This is really very nice explanation.

http://woboq.com/blog/how-qt-signals-slots-work.html

CreativeMind
  • 897
  • 6
  • 19