当前位置: 代码迷 >> QT开发 >> 多线程编程出错 求解解决思路
  详细解决方案

多线程编程出错 求解解决思路

热度:48   发布时间:2016-04-25 04:49:24.0
多线程编程出错 求解
.h文件代码:

#ifndef THREADDIALOG_H
#define THREADDIALOG_H

#include <QMainWindow>
#include<QThread>
#include<QString>
#include <QMessageBox>
#include <QPushButton>
#include<QCloseEvent>
#include<QEvent>


namespace Ui {
  class ThreadDialog;
}

class ThreadDialog : public QMainWindow
{
  Q_OBJECT

public:
  explicit ThreadDialog(QWidget *parent = 0);
  ~ThreadDialog();

private:
  Ui::ThreadDialog *ui;


protected:
  void closeEvent(QCloseEvent *event);
private slots:
  void startorStopThreadA();
  void startorStopThreadB();

};

class MyThead:public QThread
{
Q_OBJECT
public:
  virtual void Thread();
  void setMessage(const QString &message);
  void stop();
protected:
  virtual void run();
private:
  QString messageStr;
  volatile bool stopped;



};




#endif // THREADDIALOG_H


cpp文件代码

#include "threaddialog.h"
#include "ui_threaddialog.h"
#include<QThread>
#include <QMessageBox>
#include <QPushButton>
#include<QCloseEvent>
#include<QEvent>

ThreadDialog::ThreadDialog(QWidget *parent) :
  QMainWindow(parent),
  ui(new Ui::ThreadDialog)

{
  ui->setupUi(this);
  MyThead threadA;
  MyThead threadB;
  QPushButton *threadAButton;
  QPushButton *threadBButton;
  QPushButton *quitButton;
  threadA.setMessage("A");
  threadB.setMessage("B");
  threadAButton=new QPushButton(tr("Start A"));
  threadBButton=new QPushButton(tr("Start B"));
  quitButton=new QPushButton(tr("Quit"));
  quitButton->setDefault(true);

  connect(threadAButton,SIGNAL(cLicked),this,SLOT(startorStopThreadA()));
  connect(threadBButton,SIGNAL(cLicked),this,SLOT(startorStopThreadB()));
}

ThreadDialog::~ThreadDialog()
{
  delete ui;
}

void ThreadDialog::startorStopThreadA()
{
  
  if(threadA.isRunning()){
  threadA.stop();
  threadAButton->setText(tr("Start A"));
  }
  else{
  threadA.start();
  threadAButton->setText(tr("Stop A"));
  }
}

void ThreadDialog::startorStopThreadB()
{

  if(threadB.isRunning()){
  threadB.stop();
  threadBButton->setText(tr("Start B"));
  }
  else{
  threadB.start();
  threadBButton->setText(tr("Stop B"));
  }
}

void ThreadDialog::closeEvent(QCloseEvent *event)
{

  threadA.stop();
  threadB.stop();
  threadA.wait();
  threadB.wait();
  event->accept();
}
显示出很多错误,麻烦各位大侠帮忙下

------解决方案--------------------
你这文件通不过编译,
ThreadDialog::ThreadDialog(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::ThreadDialog)

{
ui->setupUi(this);
MyThead threadA;//
MyThead threadB;//这两个是局部变量
而你又在类的其它函数中调用,会提示未声明的变量错误
很显明应该将其提升为的类的变量
  相关解决方案