效果图
多线程理论
启动线程表示另开一个子线程来掷骰子,如果在主窗口线程内掷骰子,鼠标移动会卡顿,因为主窗口主线程忙着对鼠标作出反应去了。
代码项目框架
框里为子线程
tdicethread.h
重写 run()
#include "tdicethread.h"
#include <QRandomGenerator>
TDiceThread::TDiceThread(QObject *parent)
: QThread{
parent}
{
}
void TDiceThread::diceBegin()
{
//开始掷骰子
m_paused=false; // 不是暂停状态
}
void TDiceThread::dicePause()
{
//暂停掷骰子
m_paused=true; // 暂停位:真(是暂停状态)
}
void TDiceThread::stopThread()
{
//停止线程
m_stop=true; // 停止位:真
}
void TDiceThread::run()
{
//线程的事件循环
m_stop=false; //启动线程时令m_stop=false
m_paused=true; //启动运行后暂时不掷骰子
m_seq=0; //掷骰子次数
while(!m_stop) //循环主体
{
if (!m_paused)
{
m_diceValue= QRandomGenerator::global()->bounded(1,7); //产生随机数[1,6]
m_seq++;
emit newValue(m_seq, m_diceValue); //发射信号
}
msleep(500); //线程休眠500ms