【发布时间】:2022-06-11 22:55:06
【问题描述】:
Getter 和 Setter 方法在 Qt 线程中不起作用。
我从主函数中设置了QString 值,我想从QThread 中获取该值。
我的代码
main.cpp
#include "networkthread.h"
#include <QCoreApplication>
#include "msg.h"
#include <QString>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString str = argv[1];
QString strb = argv[2];
msge myObj;
myObj.setstra(str);
myObj.setstrb(strb);
NetworkThread networkThread;
networkThread.start();
int result = a.exec();
networkThread.requestInterruption();
networkThread.exit();
networkThread.wait(2000);
return 0;
}
msg.h
#include <iostream>
#include <QString>
using namespace std;
class msge
{
private:
QString stra;
QString strb;
public:
void setstra(QString s)
{
stra = s;
}
QString getstra()
{
return stra;
}
void setstrb(QString s)
{
strb = s;
}
QString getstrb()
{
return strb;
}
};
networkthread.cpp
#include "networkthread.h"
#include "msg.h"
#include <QDebug>
#include <QString>
#include <iostream>
#include <QCoreApplication>
void NetworkThread::run()
{
while (!isInterruptionRequested())
{
msge myObj;
QString str = myObj.getstra();
QString strb = myObj.getstrb();
qDebug() << str + "str first";
qDebug() << strb + "str second";
break;
}
QCoreApplication::quit();
}
networkthread.h
#ifndef NETWORKTHREAD_H
#define NETWORKTHREAD_H
#include <QThread>
#include <QString>
class NetworkThread : public QThread
{
public:
void run();
private:
};
#endif // NETWORKTHREAD_H
输出
C:\Users\prade\Documents\untitled2\release>untitled2 hello hai
"str first"
"str second"
getter 方法不起作用。
我做错了什么?
我该如何解决这个问题?
【问题讨论】:
-
你有两个对象。一个你调用 setter,另一个你调用 getter
-
仅仅因为两个
msge myObj;具有相同的名称并不能神奇地使它们成为同一个对象 -
如果没有
QThread,您将获得相同的输出 -
你能详细解释一下吗?