You can connect multiple signals to a single slot. The same signal can also be connected to multiple slots.
The signal is directly connected to other signals. (the second signal will be sent immediately after the first signal is sent .)
In short, signals and channels form a powerful component programming mechanism.
A small object-based declaration is as follows:
# Include <qobject>
Class counter: Public qobject
{
Q_object
Public:
Counter () {m_value = 0 ;}
Int value () const {return m_value ;}
Public slots:
Void setvalue (INT value );
Signals:
Void valuechanged (INT newvalue );
PRIVATE:
Int m_value;
};
This class can be notified by sending the valuechanged () signal.
It changes its status, and it has a slot that can receive signals from other objects.
All classes containing signals or slots should use q_object at the top of the Declaration. They are derived from qobject.
The slot is implemented by application developers. The following is an implementation of the slot counter: setvalue:
Void counter: setvalue (INT value)
{
If (value! = M_value ){
M_value = value;
Emit valuechanged (value );
}
}
The line containing emit sends the valuechanged () signal from the object using value as the parameter.
In the following code snippet, we create two counter objects and connect the first one using qobject: connect ().
The valuechanged () signal of the object to the setvalue () slot of the second object:
Counter A, B;
Qobject: connect (& A, signal (valuechanged (INT )),
& B, slot (setvalue (INT )));
A. setvalue (12); // A. Value () = 12, B. Value () = 12
B. setvalue (48); // A. Value () = 12, B. Value () = 48
Calling a. setvalue (12) will send a valuechanged (12) signal, which will be received by the setvalue () channel,
That is, B. setvalue (12) will be called. Then B will launch a valuechanged (), but since there is no slot
Connect to the valuechanged () signal of B, so this signal will be ignored.
Note that the setvalue () function is only available in value! = M_value, set the corresponding value and send the signal. This is
Prevent infinite loops (for example, when B. valuechanged () is connected to a. setvalue ).
A signal will be sent to each connection of the signal. If you reconnect once, two signals will be sent.
At any time, you can use qobject: disconnect () to disconnect.
Signals should be automatically generated by MOC and should not be implemented in the. cpp source file. They will never return values (so
Use void as the return value ).
The Return Value of the slot function is meaningless. The signal function is implemented by the MOC compiler. From the specific implementation perspective, the return value of the slot function is not concerned.