Showing timer in "hh:mm:ss.zzz" and reset when button clicked
-
Hi,
I have the following use case: I am receiving data from a sensor and every time a slot is called, where I write these data to a file. I would also like to isnert a timestamp in the file like a stopwatch, which begins when the Slot is called for the first time. I have the following code in my Sot:
static QTime time(QTime::currentTime()); formattedTime = QDateTime::fromTime_t(time.elapsed()/1000.0).toUTC().toString("hh:mm:ss.zzz"); // QTextStream outStream_secondDevice(&file); outStream << formattedTime <<";"<<"sensor value" << ";" << "sensor value;
- First problem: The time is shown like this, without the millliseconds :
00:00:00.000; 00:00:01.000; 00:00:01.000; 00:00:02.000; 00:00:04.000;
- The second problem is, when I "reset" my GUI via Button (without exiting the programm or the event loop in the main) and then start to transfer the data again, I expect the timer to start from the beginning (0 seconds) but it continues (because of the static keyword). So would it be enough if I add a flag "firstDataTransfer" which is true for the first time the Slot is called and then set to false and if it is true, then the timer should "restart" or is there an easier way?
- The time.elapsed is deprecated - is there another method or should I use QElapsedTimer?
-
I think QElapsedTimer is better for that situation.
And instead of a static variable in a function, how about make it a member variable that can be used in other member functions.in the header, define a member variable of QElapsedTimer
QElapsedTimer timer;
in the slot function
if(!timer.isValid()) timer.start(); QString formattedTime = QTime::fromMSecsSinceStartOfDay(timer.elapsed()).toString("hh:mm:ss.zzz");
when you "reset" the GUI
timer.invalidate();
-
I think QElapsedTimer is better for that situation.
And instead of a static variable in a function, how about make it a member variable that can be used in other member functions.in the header, define a member variable of QElapsedTimer
QElapsedTimer timer;
in the slot function
if(!timer.isValid()) timer.start(); QString formattedTime = QTime::fromMSecsSinceStartOfDay(timer.elapsed()).toString("hh:mm:ss.zzz");
when you "reset" the GUI
timer.invalidate();
-
@Bonnie said in Showing timer in "hh:mm:ss.zzz" and reset when button clicked:
I think QElapsedTimer is better for that situation.
And instead of a static variable in a function, how about make it a member variable that can be used in other member functions.in the header, define a member variable of QElapsedTimer
QElapsedTimer timer;
in the slot function
if(!timer.isValid()) timer.start(); QString formattedTime = QTime::fromMSecsSinceStartOfDay(timer.elapsed()).toString("hh:mm:ss.zzz");
when you "reset" the GUI
timer.invalidate();
Thank you very much, that's exactly what I wanted :)
Do you even have to pause and continue from there or just start and stop/reset?
And yes, just start and stop/reset.