qq_39875908
卖鱼強
采纳率0%
2017-10-27 02:36

关于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条回答

  • devmiao devmiao 4年前
    点赞 1 评论 复制链接分享
  • qq_21193563 JasonHuo_ 4年前

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

    点赞 评论 复制链接分享