Qt定時器(QTimer)的3種使用方法
Qt中定時器的使用有3種方法,
- 使用QObject類提供的定時器
- 使用QTimer類提供的定時器
- 靜態(tài)的singleShot ()函數(shù)創(chuàng)建單觸發(fā)定時器
方法一:靜態(tài)的singleShot ()函數(shù)創(chuàng)建單觸發(fā)定時器(不推薦)
singleShot函數(shù)是一個靜態(tài)函數(shù),表示只會在被調(diào)用時會執(zhí)行一次操作。其中msec參數(shù)是時間,單位為ms,借助此函數(shù)可以簡單實現(xiàn)一個定時器,定時為100s。
QTimer::singleShot(1*1000,this, &MyWidget::function);
void MyWidget::function()
{
static int num=0;
if(num < 100)
{
QTimer::singleShot(1*1000,this, &MyWidget::function);
num += 1;
ui->spinBox->setValue(num);
qDebug()<<num;
}
}
方法二:使用QTimer定時器類(這種方法普遍使用)
示例代碼:
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
tim = new QTimer();
tim->setInterval(1000);
connect(tim,SIGNAL(timeout()),this,SLOT(onTimeOut()));
tim->start();
}
void MainWindow::onTimeOut()
{
static int value = 0;
ui->progressBar->setValue(value++);
if(value > 100)
tim->stop();
}QTimer類的簡單介紹可以參考:
QTimer成員函數(shù):
QTimer::QTimer ( QObject * parent = 0, const char * name = 0 )
構造一個被稱作name,父對象為parent的定時器。
QTimer::~QTimer ()
銷毀這個定時器。
void QTimer::setInterval ( int msec )
設定定時間隔為msec毫秒。如果這個定時器信號是運行的,它將會被停止并且重新開始,否則它將會被開始。
bool QTimer::isActive () const
如果定時器正在運行,返回真,否則返回假。
void QTimer::singleShot ( int msec, QObject * receiver, const char * member ) [靜態(tài)]
這個靜態(tài)函數(shù)在一個給定時間間隔之后調(diào)用一個槽。
int QTimer::start ( int msec, bool sshot = FALSE )
開始一個msec毫秒定時的定時器。如果sshot為真,這個定時器將只會被激活一次,否則它將會持續(xù)到它被停止
void QTimer::stop ()
停止這個定時器。
void QTimer::timeout () [信號]
當定時器被激活時,這個信號被發(fā)射。
方法三:QObject中的定時器的使用,需要用到三個函數(shù)
1、 int QObject::startTimer ( int interval ) ;
這個是開啟一個定時器的函數(shù),他的參數(shù)interval是毫秒級別。當開啟成功后會返回這個定時器的ID, 并且每隔interval 時間后會進入timerEvent 函數(shù)。直到定時器被殺死。
2、 void QObject::timerEvent ( QTimerEvent * event );
當定時器超時后,會進入該事件timerEvent函數(shù),需要重寫timerEvent函數(shù),在函數(shù)中通過判斷event->timerId()來確定定時器,然后執(zhí)行某個定時器的超時函數(shù)。
3、 void QObject::killTimer ( int id );
通過從startTimer返回的ID傳入killTimer 函數(shù)中殺死定時器,結束定時器進入超時處理。
代碼:kilTimer殺死定時器后,必須再重新創(chuàng)建定時器才能啟用定時器。
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
timerid1 = startTimer(1000);
timerid2 = startTimer(2000);
}
void MainWindow::timerEvent(QTimerEvent *e)
{
if(e->timerId()==timerid1)
{
qDebug("timer1");
}
else if(e->timerId()==timerid2)
{
qDebug("timer2");
}
}
void MainWindow::on_pushButton_clicked()
{
killTimer(timerid1);
timerid1 = 0;
}
void MainWindow::on_pushButton_2_clicked()
{
timerid1 = startTimer(2000);
}到此這篇關于Qt 定時器(QTimer)的3種使用方法的文章就介紹到這了,更多相關Qt 定時器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
C語言中的abs()函數(shù)和exp()函數(shù)的用法
這篇文章主要介紹了C語言中的abs()函數(shù)和exp()函數(shù)的用法,是C語言入門學習中的基礎知識,需要的朋友可以參考下2015-08-08

