在qt项目中,我们往往需要通过udp、串口等产生数据,为了避免造成UI线程卡死,我们单独用线程来产生数据。
我们编写一个TcpClass类继承QThread
一、编写数据线程
TcpClass.h
#pragma once
#include <QThread>
using namespace std;
class TcpClass : public QThread
{
Q_OBJECT
signals:
void SendData(QString data);
public slots:
void Stopgenerate();
public:
TcpClass(QObject *parent);
~TcpClass();
void run();
QString getRandomString(int nLen);
bool status;
};
TcpClass.cpp
#include "TcpClass.h"
#include<QTime>
TcpClass::TcpClass(QObject *parent)
: QThread(parent), status(true)
{
}
TcpClass::~TcpClass()
{
}
void TcpClass::run()
{
while (status)
{
getRandomString(20);
this_thread::sleep_for(std::chrono::milliseconds(1000));
}
}
void TcpClass::Stopgenerate()
{
status = !status;//更改状态
}
//generate the random length string
QString TcpClass::getRandomString(int nLen)
{
qsrand(QDateTime::currentMSecsSinceEpoch());
const char ch[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
int size = sizeof(ch);
char* str = new char[nLen + 1];
int num = 0;
for (int nIndex = 0; nIndex < nLen; ++nIndex)
{
num = rand() % (size - 1);
str[nIndex] = ch[num];
}
str[nLen] = '\0';
QString res(str);
emit SendData(res);//触发发送信号
return res;
}
二、绑定信号和槽
#pragma once
#include <QtWidgets/QWidget>
#include "ui_LineTextChange.h"
#include"TcpClass.h"
class LineTextChange : public QWidget
{
Q_OBJECT
signals:
void Stop();
public:
LineTextChange(QWidget *parent = Q_NULLPTR);
~LineTextChange();
public slots:
void ShowDataLine(QString data);
private:
Ui::LineTextChangeClass ui;
TcpClass *tcp;
};
#include "LineTextChange.h"
#include"TcpClass.h"
LineTextChange::LineTextChange(QWidget *parent)
: QWidget(parent)
{
ui.setupUi(this);
tcp = new TcpClass(this);
connect(tcp,SIGNAL(SendData(QString)),this,SLOT(ShowDataLine(QString)));//随机字符串展示
connect(ui.lineEdit,SIGNAL(textEdited(QString)), tcp, SLOT(Stopgenerate()));//停止随机字符串生成
tcp->start();
}
void LineTextChange::ShowDataLine(QString data)
{
ui.lineEdit->setText(data);
}
LineTextChange::~LineTextChange()
{
if (tcp != NULL)
{
tcp->terminate();
tcp->deleteLater();
}
}