求助:QT5+VS2012界面编程如何在一个cpp文件中调用另一个cpp文件中的变量

项目描述:在VS+QT界面编程中新建了一个QT项目test0303,ui界面如下
ui界面
main.cpp文件保持默认不变,在test0303.h文件中定义了2个函数int Onbtn1()和int Onbtn2(),在test0303.cpp文件中connect了按钮和函数,并重写了上述2个函数。在该项目中新建了variable.h文件,定义了4个static变量。此外,在该项目中新建了QT5类MyThread,继承于QThread。

预计功能:当程序运行时,对checkbox1和checkbox2进行选择,点击pushbutton1,读取2个checkbox的状态,并qDebug相应的语句,接着点击pushbutton2,进入工作线程,根据2个checkbox的状态qDebug相应的语句。

具体问题:在程序中勾选checkbox1和checkbox2,在test0303.cpp中输出正常,进入MyThread.cpp文件中调用result2时,其值是false,为什么不是true呢?

代码:
main.cpp

#include "test0303.h"
#include <QtWidgets/QApplication>
int main(int argc, char *argv[])
{
 QApplication a(argc, argv);
 test0303 w;
 w.show();
 return a.exec();
}

variable.h

static bool result1=false;
static bool result2=false;
static int resulta;
static int resultb;

test0303.h

#ifndef TEST0303_H
#define TEST0303_H
#include <QtWidgets/QMainWindow>
#include "ui_test0303.h"
class test0303 : public QMainWindow
{
 Q_OBJECT
public:
 test0303(QWidget *parent = 0);
 ~test0303();
private slots:
 int Onbtn1();
 int Onbtn2();
private:
 Ui::test0303Class ui;
};
#endif // TEST0303_H

test0303.cpp

#include "test0303.h"
#include "variable.h"
#include <QDebug>
#include "MyThread.h"
test0303::test0303(QWidget *parent)
 : QMainWindow(parent)
{
 ui.setupUi(this);
 connect(ui.pushButton,SIGNAL(clicked()),this,SLOT(Onbtn1()));
 connect(ui.pushButton2,SIGNAL(clicked()),this,SLOT(Onbtn2()));
}
test0303::~test0303()
{
}
int test0303::Onbtn1()
{
 qDebug("button1 is pressed");
 result1=ui.checkBox1->isChecked();
 result2=ui.checkBox2->isChecked();
 if (result1==true)
 {
  qDebug("result1 is true");
  resulta=1;
 }
 else
 {
  qDebug("result1 is false");
  resultb=0;
 }
 return 0;
}

int test0303::Onbtn2()
{
 MyThread *m_thread=new MyThread(NULL);
 m_thread->start();
 return 0;

MyThread.h

#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QThread>
class MyThread : public QThread
{
 Q_OBJECT
public:
 MyThread(QObject *parent);
 ~MyThread();
 void run();
private: 
};
#endif // MYTHREAD_H

MyThread.cpp

#include "MyThread.h"
#include "variable.h"
#include <QDebug>
MyThread::MyThread(QObject *parent)
 : QThread(parent)
{
}
MyThread::~MyThread()
{
}
void MyThread::run()
{
     qDebug("run function");
     qDebug() << resulta;
 if (result2==true)
 {
      qDebug("result2 is true");
 } 
 else
 {
      qDebug("result2 is false");
 }
}

调试模式下运行结果:
button1 is pressed
result1 is true
run function
0
result2 is false

猜你喜欢

转载自blog.csdn.net/hixiaoluostudent/article/details/88086437