关于QT中子线程接收数据,主线程在lcdnumer上的显示问题

我是在QT中写的客户端,与linux中写的服务器连接,连通时自动在lcdnum上面分别显示温度和湿度。网上的例子也看了很多,但是还是一直出错,具体代码如下,有大牛给个思路吗?

#ifndef MYTHREAD_H
#define MYTHREAD_H

#include
#include
#include
#include
#include

class mythread
{
public:
mythread(QObject * parent = 0);
~mythread();
protected:
void run();
signals:
void temsignal(int);
void humsignal(int);
private:
int number;
};

#endif // MYTHREAD_H

#ifndef DIALOG3_H
#define DIALOG3_H

#include
#include
#include "mythread.h"
#include
#include
namespace Ui {
class Dialog3;
}

class Dialog3 : public QDialog
{
Q_OBJECT

public:
explicit Dialog3(QWidget *parent = 0);
~Dialog3();
private slots:
void lcdnum1set(int);
void lcdnum2set(int);
private:
QLCDNumber *lcdnum1;
//int number;
//void lcdnumset1(int num);
//void lcdnumset2(QString hum2);
private:
Ui::Dialog3 *ui;
mythread *my_thread;
};

#endif // DIALOG3_H

#include "mythread.h"
#include "mytcp.h"
#include
mythread::mythread(QObject *parent)
:QThread(parent)
{

}

mythread::~mythread()
{

}

void mythread::run()
{
qDebug()<<"开始接收温度湿度数据";
int a=1;
int b=2;
int data;
int buff1;
int buff2;
tcpsocket->waitForBytesWritten();
data=tcpsocket->write(a,sizeof(a));
if(data>0)
{
tcpsocket->waitForReadyRead();
tcpsocket->read(buff1);
emit temsignal(buff1);
sleep(1);
}
else
{
qDebug()<<"写数据失败";
}
tcpsocket->waitForBytesWritten();
data=tcpsocket->write(b,sizeof(b));
if(num {
tcpsocket->waitForReadyRead();
tcpsocket->read(buff2);
emit humsignal(buff2);
sleep(1);
}
else
{
qDebug<<"写数据失败";
}
}

#include "dialog3.h"
#include "ui_dialog3.h"
#include "mytcp.h"
#include
#include "mythread.h"
#include

Dialog3::Dialog3(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog3)
{
ui->setupUi(this);
setWindowTitle("用户界面");
my_thread=new mythread();//connect之前需要实例化
connect(my_thread,SIGNAL(temsignal(int)),this,SLOT(lcdnum1set(int)));
connect(my_thread,SIGNAL(humsignal(int)),this,SLOT(lcdnum2set(int)));
//my_thread->start();
}

Dialog3::~Dialog3()
{
delete ui;
}
void Dialog3::lcdnum1set(int num)
{
ui->lcdnum1->display(num);
}
void Dialog3::lcdnum2set(int num)
{
ui->lcdnum2->display(num);
}

2个回答

首先单独测试一下tcp通讯时候正常,然后直接在主线程上跑tcp,测试成功后再用你现在这个思路

qq_39875908
卖鱼強 通讯是正常的,我在wiget上实现了与服务器的连接,dialog1和dialog2中分别实现注册登陆,dialog3实现温度湿度的实时显示
接近 3 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问