QT Advanced Programming Tips (i)-writing efficient signal & slot communication codes

Source: Internet
Author: User

On the thread communication of QT, we all think of signal & slot mechanism. The method of using signal & slot mechanism to implement control message processing is reviewed first.

Control Message Handling

Suppose we have a Qpushbutton object on the main interface that uses UI->BTN, to implement clicked message processing for that object, you can add a slot method onbtnclicked on the main interface object MainWindow. and use the Connect method in its constructor to bind to the UI->BTN clicked message, as follows:

Mainwindow::mainwindow (qwidget* Parent): Qmainwindow (parent), UI (new Ui::mainwindow) {    ui->setupui (this);        Method one    Connect (ui->btn, &qpushbutton::clicked, this, &mainwindow::onbtnclicked);    Method two    //connect (UI->BTN, SIGNAL (clicked), this, SLOT (onbtnclicked));    ...}

void mainwindow::onbtncliced (void)
{
DoSomething ();
}

In fact, this method is very complicated. Just to handle a button message we're going to create a new slot method that will make the code bloated when the interface controls are many (even if you can design multiple control messages to share a slot function).

In the new version of Qt that supports c++11, we can use lambda functions to solve this problem gracefully. As follows:

Mainwindow::mainwindow (qwidget* Parent):    Qmainwindow (parent), UI (new Ui::mainwindow) {    setupui (this);    Use the lambda function to implement    the slot method connect (ui->btn, &qpushbutton::clicked, [&] () {        dosomething ();    });    ...}

Another benefit of using lambda functions is that you can accelerate development with the concept of closures. For example, I've done a motion control project with 32 + Qcheckbox controls on the interface, as follows:

You need to respond to the clicked message for each Qcheckbox control and change the corresponding IO port level output. My practice is to tab the controls and name the first control Ui->iochk, and then encode the following:

typedef qcheckbox   *F_QCB; #define F_qnext (W)  (W->nextinfocuschain ())

...

Mainwindow::mainwindow (qwidget* Parent):
Qmainwindow (parent), UI (new Ui::mainwindow)
{
Setupui (UI);
  
...
F_QCB cb = ui->iochk;
for (int i = 0; i <; ++i)
{
Connect (CB, &qcheckbox::clicked, [=] (bool s) {
Setio (i, s); Change the output level of the I port to S
});
CB = F_qnext (CB);
}
...
}

To read the above procedure, you need some knowledge of the lambda functions of the C++11 standard, which captures the I variable value using the Value capture method to form the closure function, which is bound to the different qcheckbox clicked messages.

Inter-thread communication

For a long time, I thought Qt's signal & slot mechanism only applies to one-way asynchronous communication. In fact, it can be designed for synchronous communication with the return.

One case is as follows: The worker thread needs to synchronously extract the parameter information on the interface at runtime (assuming that the value of the Qspinbox on the interface is extracted), and to ensure that the interface responds and the work threads are running continuously.

One possible implementation is to define a request message on an object on the worker thread, bind to the response slot in the MainWindow, and then define a answer message in MainWindow. A onanswer slot that is bound to an object on a worker thread. The communication process is as follows:

1. Worker threads need interface parameter values, send request message

2. The main thread receives the request message and begins the execution of the response slot method

3. In the response function, get the value of the interface control and send the answer message

4. The worker thread receives the answer message, calls the Onanswer slot method, restores the previous run process

This method is clear, but the coding implementation is too cumbersome. My implementation is to implement a message in the worker thread such as request (QString req, qvariant& Arg), and then take QT:: The blockblockingqueuedconnection mode is connected to the response Groove method of the MainWindow. The code is as follows:

Workerthread Declaration Header file:

#ifndef __worker_thread_h
#define __worker_thread_h

Class Workerthread:public Qthread {
Public
...
@Override
void run ();

Private
For communication
Class Inthreadobject;
Inthreadobject *ito;
...
}

#endif

Workerthread implementation:

Class Workerthread::inthreadobject:public Qobject {
Q_object

Signals:
void Request (QString req, qvariant& Arg);
}

void Workerthread::run ()
{
Ito = new Inthreadobject;
......
Note the following connection uses the Qt::blockingqueuedconnection option
Connect (Ito, &inthreadobject::request, Mainwindow::response,
......
Synchronizing get interface parameter values
qvariant var;
Ito->request ("Param.level", Var);
This will wait until the main thread executes the response function.
int param = Var.toint ();
......
}

MainWindow Related implementations:

void Mainwindow::response (QString req, qvariant& ans)
{
if (req = = "Param.level")
{
Get control values and put them into ans reference variables
Ans.setvalue (Ui->levelspin->value ());
}
}

This experience is shared, with specific technical details such as QT's message and slot mechanism, C++11 's lambda function, and a separate study for the reader.

This article links: http://www.cnblogs.com/wenris/p/4447481.html.

Wenris; Contact: <[email protected]>

Farewell O (∩_∩) o

QT Advanced Programming Tips (i)-writing efficient signal & slot communication codes

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.