On the main thread, you can control the child thread start, stop, Zero
If a child thread starts, it sends a number to the main thread every second, allowing the main thread to update the number on the interface.
Program:
On the code:
[CPP]View Plaincopyprint?
- #include <QtGui>
- #include <QtCore>
- #include <windows.h>
- Class Thread: Public qthread
- {
- Q_object
- Private
- int number;
- Protected
- void Run ();
- Public
- Thread (Qobject *parent=0);
- ~thread ();
- Signals:
- void updatesignal (int num);
- Public Slots:
- void Resetslot ();
- };
- Class Widget: Public qwidget
- {
- Q_object
- Private
- Qlabel *label;
- Qpushbutton *startbutton;
- Qpushbutton *stopbutton;
- Qpushbutton *resetbutton;
- Thread *mythread;
- int number;
- Public
- Widget (Qwidget *parent = 0);
- ~widget ();
- Signals:
- void Resetsignal ();
- Public Slots:
- void Clearslot ();
- void Startslot ();
- void Stopslot ();
- void Updateslot (int num);
- };
- Thread::thread (Qobject *parent)
- {
- Number = 0;
- }
- Thread::~thread ()
- {
- }
- void Thread::run ()
- {
- While (1)
- {
- //Turn on a dead loop and let number increment by 1 per second and notify the main interface update by sending updatesignal signal
- Emit updatesignal (number);
- number++;
- Sleep (1);
- }
- }
- void Thread::resetslot ()
- {
- Number = 0;
- Emit updatesignal (number);
- }
- Widget::widget (Qwidget *parent)
- {
- //SET interface layout
- Startbutton = New Qpushbutton ("start");
- Stopbutton = New Qpushbutton ("Stop");
- Resetbutton = New Qpushbutton ("reset");
- label = New Qlabel ("Empty");
- MyThread = new Thread;
- Qvboxlayout *layout = new Qvboxlayout;
- Layout->addwidget (label);
- Layout->addwidget (Startbutton);
- Layout->addwidget (Stopbutton);
- Layout->addwidget (Resetbutton);
- SetLayout (layout);
- //Connect the respective signal bad
- Connect (Stopbutton, SIGNAL (clicked ()),
- This , SLOT (Stopslot ()));
- Connect (Startbutton, SIGNAL (clicked ()),
- This , SLOT (Startslot ()));
- Connect (Resetbutton, SIGNAL (clicked ()),
- This , SLOT (Clearslot ()));
- Connect (MyThread, SIGNAL (updatesignal (int)),
- This , SLOT (updateslot (int)));
- Connect (this, SIGNAL (Resetsignal ()),
- MyThread, SLOT (Resetslot ()));
- Setwindowtitle ("Thread Test");
- Resize (200, 200);
- Mythread->start ();
- }
- Widget::~widget ()
- {
- }
- void Widget::startslot ()
- {
- Mythread->start ();
- }
- void Widget::stopslot ()
- {
- Mythread->terminate ();
- }
- void Widget::updateslot (int num)
- {
- Label->settext (Qstring::number (num));
- }
- void Widget::clearslot ()
- {
- Emit resetsignal ();
- }
- #include "Main.moc"
- int main (int argc, char **argv)
- {
- Qapplication app (argc, argv);
- Widget *widget = new Widget;
- Widget->show ();
- return app.exec ();
- }
http://blog.csdn.net/small_qch/article/details/6681907
Communication between a GUI (master) thread and a child thread (communication with a signal slot)