QT数据线程的创建和使用

本文介绍了一个Qt项目中如何通过创建独立线程避免UI阻塞,以TCPClass为例,展示如何生成并发送随机字符串数据。通过QThread实现数据生成线程,使用信号和槽机制将数据传递到UI,并提供停止生成数据的接口。
摘要由CSDN通过智能技术生成

在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();
	}

}

三、效果展示

在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值