문제

I'm learning Qt and I'm having lots of fun with the signals-slotpattern. The question that I have is that, are signals and slots simply syntactic sugar for event listeners and handlers or what happens in the background is of different nature? If the later, what is the fundamental difference?

도움이 되었습니까?

해결책 2

Are signals and slots syntactic sugar or there is more to them? The question that I have is that, are signals and slots simply syntactic sugar for event listeners/handlers

No, the mean reason for their existence is decoupling of the emission and handling.

or what happens in the background is of different nature?

The idea is that you separate the emission from the handling of a certain "event". If you consider the direct function calls as an alternative, I would like to point that out, with them, the code responible for the emission would need to be aware of the code that actually handles the "signal". That is the two parts would be too tight too each other.

It would not be possible to dynamically add another handler for the signal without changing the code that is responsible for the signal emission. Imagine an example like this:

  • Some part of the code emits a signal "fruit arrived"

  • This code would directly call the "wash fruit" method.

What if someone would like to add a method to count the number of fruits?

  • The previous code would need to be modified to include the direct call to that method.

With the signal-slot mechanism, you would not need to touch the original code. You could just simple connect your new slot to the existing signal from an entirely different piece of code. This is called good design and freedom.

This is especially useful when you have libraries like Qt that can emit signals all around without knowing about the Qt applications in advance. It is up to the Qt applications how to handle the signals, on their own.

In addition, this pattern also makes the application more responsive and less blocking, which would be the case with direction function calls. This is because of the existence of the event loop on which the Qt signal-slot mechanism is built upon. Surely, you could use threading with direct calls, too, but it becomes a lot more work and difficult to maintain than it would be necessary in an ideal world.

So, as partially already touched, there is a QtEventLoop in the background queuing up these events for processing, although it is possible to execute "direct calls", too.

The really background internal implementation code can be found there, and in moc (meta object compiler). Moc is basically creating a function for signals which you do not define a body for, so you just declare them in the QObject subclasses when you need it.

You can read more upon the topic in here, but I think my explanation could get you going:

Qt Signals & Slots

QtDD13 - Olivier Goffart - Signals and Slots in Qt 5

How Qt Signals and Slots Work

How Qt Signals and Slots Work - Part 2 - Qt5 New Syntax

Signals and Slots in Qt5

Using the Meta-Object Compiler (moc)

다른 팁

This is not just syntactic sugar. There is a real work in the background of Qt signals/slots. This work is done by the MOC (Meta-Object Compiler). This is the reason there is a process on all of your C++ header files that contains class with Q_OBJECT macros.

The "hard part" of signals/slots is when you are in a multithreading context. Indeed, the Qt::ConnectionType argument of connect() function, which is Direct (e.g. direct call of the function) in a single-threaded environment, is Queued in a if sender and emitter aren't in the same thread. In this case, the signal must be handled by the Qt event loop.

For more details: http://qt-project.org/doc/qt-4.8/signalsandslots.html

The signals and slots are a way to decouple the method call from the called method. They are not syntactic sugar at all since they add no new syntax to the C++ language. A signal emission is a method call. A slot is a plain old instance method. The code that links the two is plain old C++. Nothing new here - no sugar of any kind.

Most of what you call "the syntactic sugar" is akin to comments - those are empty defines (Q_SLOT, Q_SIGNAL, signals, slots) used to mark the methods for processing by the meta object compiler (moc). Moc generates introspection information and signal implementations based on normal C++ syntax of the declarations (with some limitations).

I claim that this is not syntactic sugar since moc understands regular C++ and generates introspection data based not on any syntactic sugar, but on usual instance method declarations. The "sugar" is there to avoid the premature pessimization of having moc generate metadata for everything in a class's declaration. It also lets moc ignore the method definitions - otherwise it'd need to parse them, and assume that methods without definitions are signals.

The emit macro is only for human consumption and is merely an indication that a method call is really a signal emission. It's not used by moc. It's defined to be empty.

The Q_OBJECT and Q_GADGET macros declare some class members used to access the metadata. They are, arguably, the only piece of real "sugar" since it saves you from having to type out a few lines of declarations.

There's quite a bit of code potentially involved in making it work.

  1. A signal:

    • is an instance method whose implementation is generated by moc,

    • has full introspection information about its name and arguments. This is available as an instance of QMetaMethod.

  2. A slot:

    • is an instance method whose implementation you provide,

    • similarly has full introspection information.

The metainformation is available at runtime and can be enumerated and used by code that has no prior knowledge of the signal's nor slot's signature.

When you emit a signal, you simply call the method generated by moc. This method invokes Qt library code that acquires relevant mutexes, iterates the list of attached slots, and executes the calls, acquiring additional mutexes as needed along the way. Doing this properly requires care, since the sender and receiver objects can reside in different threads. One has to avoid delivery of slot calls to non-existent objects. Oh, you don't want deadlocks either. This requires some forethought.

Since both signals and slots are just methods, you can certainly connect signals to other signals - the underlying mechanism doesn't care what gets called, it's just an invokable method. Non-invokable methods are those without metadata.

A slot gets invoked when the relevant signal is emitted. A signal emission is just a method call to the generated body of the signal. This is different from event-listener pattern, since the slot invocation can be either immediate (so-called direct connection) or deferred to the event loop (so-called queued connection). A queued slot call is implemented by copying the arguments and bundling them in a QMetaCallEvent. This event is "converted" back into a method call by QObject::event. This happens when the event loop delivers the event to the target object.

The metadata contains more than just signal and slot signatures. It also allows you to default- and copy-construct signal/slot parameter types - this is necessary to implement the queued calls. It also contains key-value pairs for enumerations - that's what makes Qt rather easy to script. All enum values passed to Qt methods can be looked up by name, at runtime!

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top