使用QTimer显示计时器

时间:2014-10-29 14:47:05

标签: c++ qt

我创建了一个名为aTimer的类,它继承自QTimer。我希望能够将经过的时间存储到TimeElapsed类型的int变量中。然后,我希望在主窗口打开时自动启动计时器,并显示其中经过的时间。

我认为我使用了错误的计时器,我对Qt中使用哪些工具感到困惑,因为有不同的处理时间的方法。可以这么说,我想要一种观察类型的模块,允许我手动启动和停止时间而无需上限(或与Timer的情况间隔)。我该怎么办?到目前为止,尝试使用QTimer毫无结果。

1 个答案:

答案 0 :(得分:1)

您不需要为此任务派生类。我可能会使用QTimerQElapsedTimer

在主窗口构造函数中创建它们,并根据应更新时间的频率设置QTimers间隔。还将其timeout()信号连接到更新显示值的函数。在此功能中,您可以从QElapsedTimer获取已用时间并更新显示。

// *.h
QTimer* timer;
QElapsedTimer *eltimer;

// *.cpp
constructor(){
    this->timer = new QTimer(this);
    this->timer->setInterval(1000);
    connect(this->timer, SIGNAL(timeout()), this, SLOT(update_ui()));
    this->timer->start();

    this->eltimer = new QElapsedTimer(this);
    this->eltimer->start();
}

SLOT update_ui(){
    qint64 msecs_elapsed = this->eltimer->elapsed();
    // Insert value into ui object
}

当然,您可以创建一些按钮start()stop() QTimer

相关问题