注意:在定时器中
1、this->m_switch = this->startTimer(1000);括号里面的是毫秒计算
2、在多线程中的 QThread::sleep(1);括号里面是以秒来计算
QThread::msleep(1);这个时候括号里是以毫秒来计算
新建一个ui界面的demo
.h(头文件中)
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QLabel>
#include <QTimerEvent>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
protected:
//这是一个虚函数,从QEvent继承而来.
void timerEvent(QTimerEvent*event);
private slots:
void startTimerSlot();//两个槽函数,执行开始和停止的功能
void stopTimerSlot();
private:
Ui::Widget *ui;
int m_switch;//设置定时器ID
bool m_Status = false;//设置当前的状态,默认为false
};
#endif // WIDGET_H
在.cpp(源文件中)
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
//连接信号与槽.
connect(ui->startButton, SIGNAL(clicked()), this, SLOT(startTimerSlot()));
connect(ui->stopButton, SIGNAL(clicked()), this, SLOT(stopTimerSlot()));
}
Widget::~Widget()
{
delete ui;
}
void Widget::timerEvent(QTimerEvent*event)
{
//判断当前定时器对应的是哪个Id.
if (event->timerId() == this->m_switch)
{
if (this->m_Status == false)
{
//更改按钮上的文字
ui->toolButton->setText("123");
this->m_Status = true;
}
else
{
//更改按钮上的文字
ui->toolButton->setText("234");
this->m_Status = false;
}
}
}
//开始
void Widget::startTimerSlot()
{
//设置定时器,返回一个timerld.注意单位为毫秒,1000毫秒等于1秒.
this->m_switch = this->startTimer(1000);
}
void Widget::stopTimerSlot()
{
//停止定时器.
this->killTimer(this->m_switch);
}
在main函数中:
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}
现象是在点击完开始按钮之后,就会实现切换的功能 :
参考:https://blog.youkuaiyun.com/qq_37233607/article/details/78218596
并作出一些修改!