学习QT有一阵子了,只是看到别人用各种类的函数,心中一直想看看各个类的具体实现功能。今天我将从QTimer讲起,一点一滴的分解QT,分析各个类的常用函数功能。
QTimer (重复和单发计时器)
通常来讲,应用QTimer时,先创建一个QTimer类,利用connect将timeout()与对应槽函数链接,在调用start()函数设置定时器世界间隔d,这样,每经过d时间后,定时器会emit一个timeou(),相应的槽函数就会被触发,直到调用stop()函数停止。
经典应用如下:
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(function));
timer->start(1000);
当然,我们也可以不用定义QTimer类,直接调用QTimer的成员函数singleShot(),定时器只执行一次
QTimer::singleShot(200, this, SLOT(updateCaption()));
下面具体介绍QTimer的 成员函数,属性,信号与槽函数等
1 属性
active:(const bool) 激活属性,定时器运行时返回true,否则返回false;
访问函数:bool isActive() const
interval: (int) 时间间隔, 默认值是0,当定时器默认值为0时,当所有系统事件被处理后,
定时器会暂停, 访问函数 : int interval() const void setInterval(int msec)
remaining Time: const int 返回当前计时到超时间的值,计时器没激活时返回-1, 超时返回0
访问函数: int remainingTime() const
singleShot:bool 查看是否为单发计时器, 访问函数: bool isSingleShot() const
void setSingleShot(bool singleShot)
timerType: Qt::TimerType 时间类型,控制时间精度,默认Qt::CoarseTimer
访问函数: Qt:TimerType timerType() const void setTimerType(Type atype)
2 成员函数
void QTimer::singleShot(int msec, const QObject * receiver, const char * member)
void QTimer::singleShot(int msec, Qt::TimerType timerType, const QObject * receiver, const char * member)
在规定的时间间隔调用函数
事例:
#include <QApplication>
#include <QTimer>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QTimer::singleShot(600000, &app, SLOT(quit()));
...
return app.exec();
}
在10分钟后,应用程序将关闭。
void QTimer::start(int msec)
void QTimer::start()
启动或重启计时器,msec为时间间隔,没有参数时,时间间隔为0
void QTimer::stop()
停止计时器
void QTimer::timeout()
当定时器时间到时,信号被发射。
int QTimer::timerId()
返回正在运行的计时器的ID号,否则返回-1