0 the signal and slot __QT of QT core mechanism and principle of QT4 programming in basic science

Source: Internet
Author: User
Tags emit

Signal and Groove

The signal and slot mechanism is one of the core mechanisms of QT, so it is necessary to understand the signals and slots in order to master QT programming. Signal and slot is an advanced interface, they are applied to the communication between objects, they are the core characteristics of QT, and Qt is different from the other similar toolkit is one of the important places.

In other GUI toolkits that we know, widgets have a callback function that responds to the action they trigger, which is usually a pointer to a function. The above mechanism is replaced by signals and slots in Qt.

1. Signal (signal)

When the state of an object changes, the signal is emitted by an object (emit). Only the class that defines the signal or its derived class can emit the signal. When a signal is emitted, its associated slot is executed as if it were a normal function call. The signal-slot mechanism is independent of any GUI event loops. The launch function (emit) is returned only if all slots are returned correctly.

If there are multiple slots associated with a signal, the slots will be executed one after another when the signal is emitted, but the order in which they are executed will be indeterminate, and we cannot specify the order in which they are executed.

The declaration of the signal is made in the header file, and the MOC tool will be careful not to define the signal in the implementation file. QT uses the SIGNALS keyword to identify the signal declaration area and then declare its own signal. For example, several signals are defined below:

void Yoursignal ();
void yoursignal (int x);

In the above statement, signals is the key word for QT. The next line of void Yoursignal (); The signal yoursignal is defined, the signal is not carrying parameters, the next line of void yoursignal (int x), the signal yoursignal (int x) is defined, but it carries an integer parameter, which is similar to overloading.

Note that the declaration of a signal and slot function is typically in the header file, and the statement must be q_object at the beginning of the class declaration, which will tell the compiler that the MOC tool must be extended before compiling. The keyword signals points out the declaration of the subsequent start signal, where signals is in the plural form rather than the singular, and siganls has no public, private, protected attributes, which is different from slots. In addition, the signals, slots keywords are defined by QT itself, not keywords in C + +.

Also, the declaration of a signal is similar to a declaration of a function rather than a statement of a variable, with a type on the left, a bracket to the right, and, if you want to pass the argument to a slot, specify the type of each form parameter in parentheses, and of course the number of formal arguments can be more

In formal terms, the declaration of a signal is the same as a normal C + + function, but the signal does not define a function implementation. In addition, the return type of the signal is void, and the return value of the C + + function can have a rich type.

Note that the signal code is automatically generated by MOC, MOC translates it into standard C + + statements, and the C + + preprocessor considers itself dealing with standard C + + source files. Therefore, we do not in their own C + + implementation of the file implementation signal.

2. Groove (slot)

Slots are ordinary C + + member functions that can be invoked normally, unlike the signals (signal) that can be associated with them. When the signal associated with it is launched, the slot is invoked. Slots can have parameters, but the parameters of slots cannot have default values.

Slots also have the same access as normal member functions. The access to the slot determines who can connect to it. Typically, slots are also divided into three types, namely public slots, private slots, and protected slots.

Public slots: The slot declared in this code section means that any object can connect the signal to it. This is useful for component programming: You generate a lot of objects that don't know each other, connect their signals and slots so that the information can be transmitted correctly, and like a train model on a railroad track that a child likes to play on, open it up and let it run.

Protected slots: The slot declared within this code section means that the current class and its subclasses can associate the signal with it. These slots are only part of the implementation of the class, not its interface with the outside world.

Private slots: The slot declared within this code section means that only the class itself can associate the signal with it. This means that these slots are very close to this class, and even its subclasses do not have the trust to connect right.

Usually, we use public and private declaration slots is more common, we recommend that try not to use the protected keyword to modify the properties of the slot. In addition, slots can also be declared as virtual functions.

The declaration of the slot is also done in the header file. For example, several slots are declared below:

Public Slots:
void Yourslot ();
void Yourslot (int x);

Note that the keyword slots indicates the subsequent opening of the slot, where slots is also in the plural form.

3. signal and Groove connection

Slots and ordinary C + + member functions are almost the same-can be virtual functions, can be overloaded, can be shared, protected, or private, and can also be called directly by other C + + member functions, and their arguments can be of any type. The only difference is that the slot can also be connected to the signal, in which case the slot is automatically invoked whenever the signal is emitted.

The Connect () statement will look something like the following:

Connect (sender,signal (SIGNAL), Receiver,slot (SLOT));

The sender and receiver here are pointers to qobject, and signal and slot are function names without arguments. In fact, SIGNAL () macros and slot () convert their arguments to the corresponding strings.

So far, in the instances we've seen, we've connected different signals to different slots. But there are some other possibilities that need to be considered here.

⑴ a signal can connect multiple slots

Connect (slider,signal (valuechanged (int)), Spinbox,slot (setValue (int)));
Connect (slider,signal (valuechanged (int)), This,slot (updatestatusbarindicator (int)));

When the signal is fired, the slots are called one after another in an indeterminate order.

⑵ multiple signals can be connected to the same slot

Connect ()

This slot will be invoked regardless of which signal is fired.

⑶ a signal can be connected to another signal

Connect (lineedit,signal (textchanged (const Qstring &)), This,signal (UpdateRecord (const Qstring &));

When the first signal is fired, a second signal is emitted. In addition, the connection between signal and signal and the connection between signal and groove are difficult to distinguish.

⑷ connections can be removed

Disconnect (lcd,signal (overflow ()), This,slot (Handlematherror ()));

This is rarely used because QT automatically removes all connections associated with this object when the object is deleted.

⑸ to successfully connect the signal to the slot (or to another signal), their parameters must have the same order and the same type

Connect (ftp,signal (rawcommandreply (int,const QString &)), This,slot (processreply (int,const QString &));

⑹ if the signal has more parameters than the slot it is connected to, then the extra parameters will be simply ignored.

Connect (ftp,signal (rawcommandreply (int,const Qstring &)), This,slot (int));

Also, if the parameter type does not match, or if the signal or slot does not exist, Qt warns at run time when the application is built with debug mode. Similarly, QT warns if a parameter name is included in the name of the signal and slot.

The signal and slot mechanism itself is implemented in the Qobject, and is not limited to the graphical user interface programming. This mechanism can be used in any qobject subclass.

The macro signal () that must use QT when specifying a signal signal must use the macro slot () when the slot function is specified. If the transmitter and receiver belong to the same object, then the receiver parameter can be omitted in the connect call.

For example, the following defines two objects: the Label object label and the ScrollBar object scroll, and the valuechanged () signal is associated with the Setnum () of the Label object, and the signal also carries an shaping parameter so that the label always shows the value of where the scroll bar is located.

Qlabel *label = new Qlabel;
  Qscrollbar *scroll = new Qscrollbar;
  qobject::connect (scroll, SIGNAL (valuechanged (int)),
Label, SLOT (Setnum (int)));

4. signal and slot connection example

The following is an example of a QObject subclass:

Class Bankaccount:public QObject
{
Q_object
Public
BankAccount () {curbalance = 0;}
int balance () const {return curbalance}
Public Slots:
void setbalance (int newbalance);
Signals:
void balancechanged (int newbalance);
Private
int currentbalance;
};

Similar to the style of most C + + classes, the BankAccount class has constructors, balance () read functions, and setbalance () set functions. It also has a balancechanged () signal that will be emitted when the account balance changes. When a signal is emitted, the slot connected to it is executed.

The Set function is declared in a public slot, so it is a slot. A slot can be used as a member function, called as any other function, or connected to a signal. The following is the implementation process for the setbalance () slot:

void bankaccount::setbalance (int newbalance)
{
{
Currentbalance = newbalance;
Emit balancechanged (currentbalance);
}
}

Statement emit balancechanged (currentbalance), the balancechanged () signal is emitted and the current new balance is used as its parameter.

Keyword emit are similar to "signals" and "slots", provided by Qt and converted by the C + + preprocessor into standard C + + statements.

The following example shows how to connect two BankAccount objects:

BankAccount x, y;
Connect (&x, SIGNAL (balancechanged (int)), &y, SLOT (int));
X.setbalance (2450);

When the balance in X is set to 2450, the system emits a balancechanged () signal. Setbalance () slot in Y when you receive this signal, set the balance in Y to 2450. An object's signal can be connected to several different slots, and multiple signals can also be connected to a slot in a particular object. Signals and slots with the same parameter type can be connected to each other. The number of parameters of the slot can be less than the number of parameters of the signal, then the extra parameters will be ignored.

5. Issues to be noted

Signal and slot mechanism is more flexible, but some limitations we must understand, so in the actual use of the process can be targeted to avoid some errors. Here is a brief description of the situation.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.