To measure the execution time inside the calculation function and constantly spitting with signals about the current time is not optimal. It is more correct to inherit the widget from QLabel, in which when you call the start()
slot start()
timer will start with the time update. At the end of the calculation, stop the timer and display the time received from the calculation function. Something like this:
TimeLabel.cpp
#include "timelabel.h" TimeLabel::TimeLabel(QWidget *parent) : QLabel(parent) { } void TimeLabel::timerEvent(QTimerEvent *e) { setText(QTime(0,0).addMSecs(time.elapsed()).toString("m:ss.zzz")); //эту конструкцию лучше обернуть в отдельную функцию и сделать нормальный выбор формата вывода } void TimeLabel::start() { //TODO проверить, не запущен ли уже таймер, отреагировать time.restart(); timerID = startTimer(100); //запоминаем идентификатор запущенного таймера чтобы потом можно было его прибить } void TimeLabel::stop(int ms) //сюда можно передать время работы функции и оно будет выведено в качестве текста { killTimer(timerID); if (ms > 0) setText(QTime(0,0).addMSecs(ms).toString("m:ss.zzz")); }
TimeLabel.h
#ifndef TIMELABEL_H #define TIMELABEL_H #include <QLabel> #include <QTimer> #include <QTime> class TimeLabel : public QLabel { Q_OBJECT public: explicit TimeLabel(QWidget *parent = 0); protected: void timerEvent(QTimerEvent *e); private: int timerID; QTime time; signals: public slots: void start(); void stop(int ms = 0); }; #endif // TIMELABEL_H
With this approach, such labels can be crammed into a form at least a hundred and monitor the execution time of anything. Before starting the calculation, call ui->label->start()
, after the end, call (by signal, or directly) stop
, passing the runtime function, or clear the text, if necessary.
emit updateWorkTime(Milliseconds);
- Alexander