我正在寻找一个可以启动,停止的时钟/计时器,并且可以返回自启动以来经过的时间。是否有一个小部件可以完成所有这些事情?
THX
答案 0 :(得分:3)
您可以使用QTime
或QElapsedTimer
,但它们不是QObject
,因此如果您需要,则需要将它们包装在QObject
课程中能够通过Qt信号启动和停止它们。
class Timer : public QObject {
Q_OBJECT
public:
explicit Timer(QObject *parent = 0): QObject(parent) {}
public slots:
void start() {
time.start();
}
void stop() {
emit elapsed(time.elapsed());
}
signals:
void elapsed(int msec);
private:
QTime time;
};
答案 1 :(得分:0)
请查看此示例,以及课程QTimer
//This class will inherit from QTimer
class Timer : public QTimer
{
//We will count all the time, that passed in miliseconds
long timePassed;
Q_OBJECT
public:
explicit Timer(QObject *parent = 0) : QTimer(parent)
{
timePassed = 0;
connect(this, SIGNAL(timeout()), this, SLOT(tick()));
}
private slots:
//this slot will be connected with the Timers timeout() signal.
//after you start the timer, the timeout signal will be fired every time,
//when the amount interval() time passed.
void tick()
{
timePassed+=interval(); //we increase the time passed
qDebug()<<timePassed; //and debug our collected time
}
};
在您的主要申请中:
Timer * timer = new Timer(this);
timer->setInterval(1000);
timer->start();
这将创建一个Timer对象,将其间隔设置为1秒,然后启动它。您可以根据需要将多个插槽连接到timeout()信号,也可以创建自定义信号。您可以按timer->stop();
我希望它有所帮助!