日期:2014-05-16 浏览次数:21452 次
转载请注明出处:http://blog.csdn.net/feng1790291543
主线程与子线程通信主要是通过Qt上的G ui按钮,触发使得主线程上的信息发送到子线程中,并且时刻监测线程的运行情况
主线程,头文件:
#ifndef MANAGEWIDGET_H #define MANAGEWIDGET_H #include <QtGui/QWidget> #include <QtCore> //#include "childwidget.h" //#include "simplethread.h" //class ChildWidget; class SimpleThread; namespace Ui { class ManageWidget; } class ManageWidget : public QWidget { Q_OBJECT public: ManageWidget(QWidget *parent = 0); ~ManageWidget(); private: Ui::ManageWidget *ui; //ChildWidget *child; QThread *child; SimpleThread *simple; private slots: void on_pushButton_clicked(); void on_pushButtonRunChild_clicked(); void on_pushButtonSend_clicked(); void StartReceive(); void FinishReceive(); signals: void SignalChild(QString str); }; #endif // MANAGEWIDGET_H
#include "managewidget.h" #include "ui_managewidget.h" #include "childwidget.h" #include "simplethread.h" ManageWidget::ManageWidget(QWidget *parent) : QWidget(parent), ui(new Ui::ManageWidget) { ui->setupUi(this); simple=new SimpleThread; //child=new ChildWidget; child=new QThread; connect(this,SIGNAL(SignalChild(QString)),simple,SLOT(print_str(QString))); connect(child,SIGNAL(started()),this,SLOT(StartReceive())); //connect(child,SIGNAL(finished()),this,SLOT(FinishReceive())); } ManageWidget::~ManageWidget() { delete ui; } void ManageWidget::StartReceive() { qDebug()<<"thread is starting!"; } void ManageWidget::FinishReceive() { qDebug()<<"thread is finishing!"; } void ManageWidget::on_pushButtonSend_clicked() { QString str=ui->lineEditContent->text(); emit SignalChild(str); return ; } void ManageWidget::on_pushButtonRunChild_clicked() { qDebug()<<"Main Thread Id is "<<QThread::currentThreadId(); simple->moveToThread(child); child->start(); return ; } void ManageWidget::on_pushButton_clicked() { qDebug()<<"first isRuning---->"<<child->isRunning(); qDebug()<<"first isFinishing---->"<<child->isFinished(); child->quit(); child->wait(); qDebug()<<"second isRuning--->"<<child->isRunning(); qDebug()<<"second isFinishing---->"<<child->isFinished(); child->deleteLater(); delete child; }
#ifndef CHILDWIDGET_H #define CHILDWIDGET_H #include <QThread> #include <QtCore> class ChildWidget : public QThread { Q_OBJECT public: ChildWidget(); void run(); }; #endif // CHILDWIDGET_H
#include "childwidget.h" ChildWidget::ChildWidget() { } void ChildWidget::run() { QString str="hello zhangsan"; qDebug()<<"子线程中的的run() is"<<str; exec(); return ; }