我在QT制作精密计时器时遇到的麻烦很少,我需要在显示" HH:MM:SS"的QLabel中进行。自按下一个按钮后已经过去了,有没有人有一个简单的方法来做到这一点?非常感谢你!
答案 0 :(得分:1)
开始QElapsedTimer
。然后启动QTimer
,并将其超时信号连接到获得elapsedTimer.elapsed()
的插槽,将自计时器启动以来的毫秒转换为秒,分钟和小时,并更新标签。
class Chronometer {
QElapsedTimer t;
public:
void restart() { t.restart(); }
QTime getTime() { return QTime(0,0).addMSecs(t.elapsed()); }
};
class ChronoUI : public QWidget {
Q_OBJECT
Chronometer c;
QTimer t;
QLabel * l;
QPushButton * startB, * stopB;
public:
ChronoUI() {
QVBoxLayout * ly = new QVBoxLayout;
setLayout(ly);
ly->addWidget(l = new QLabel(this));
l->setText(QTime(0, 0).toString());
ly->addWidget(startB = new QPushButton("start", this));
ly->addWidget(stopB = new QPushButton("stop", this));
connect(&t, SIGNAL(timeout()), this, SLOT(updateTime()));
connect(startB, SIGNAL(clicked(bool)), this, SLOT(start()));
connect(stopB, SIGNAL(clicked(bool)), &t, SLOT(stop()));
}
public slots:
void updateTime() { l->setText(c.getTime().toString()); }
void start() {
l->setText(QTime(0, 0).toString());
c.restart();
t.start(1000);
}
};
或者如果您不想使用QElapsedTimer
,您可以以类似的方式使用QTime
,虽然它的分辨率较低,QTime
只能达到毫秒级,虽然QElapsedTimer
在某些平台上可以达到纳秒,如果你想要的最低值是秒,那么这些都是过度的:
class ChronoUI : public QWidget {
Q_OBJECT
QTime startTime;
QTimer t;
QLabel * l;
QPushButton * startB, * stopB;
public:
ChronoUI() {
QVBoxLayout * ly = new QVBoxLayout;
setLayout(ly);
ly->addWidget(l = new QLabel(this));
l->setText(QTime(0, 0).toString());
ly->addWidget(startB = new QPushButton("start", this));
ly->addWidget(stopB = new QPushButton("stop", this));
connect(&t, SIGNAL(timeout()), this, SLOT(updateTime()));
connect(startB, SIGNAL(clicked(bool)), this, SLOT(start()));
connect(stopB, SIGNAL(clicked(bool)), &t, SLOT(stop()));
}
public slots:
void updateTime() { l->setText(QTime(0, 0).addMSecs(startTime.elapsed()).toString()); }
void start() {
l->setText(QTime(0, 0).toString());
startTime.restart();
t.start(1000);
}
};