Last active
November 9, 2017 20:24
-
-
Save peteristhegreat/d17e842d55653305baeb3f4911aab251 to your computer and use it in GitHub Desktop.
QTime subclass that has human readable output that shows hours, minutes, seconds, and has a start/stop/pause button that works as expected.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef MYTIME_H | |
#define MYTIME_H | |
#include <QTime> | |
#include <QString> | |
class MyTime : public QTime | |
{ | |
public: | |
// explicit MyTime(QObject *parent = 0) | |
// { | |
// m_paused = false; | |
// } | |
int elapsed() const | |
{ | |
if(m_paused) | |
return m_offset; | |
else | |
return QTime::elapsed() + m_offset; | |
} | |
int restart() | |
{ | |
int retVal; | |
if(m_paused) | |
retVal = m_offset; | |
else | |
retVal = QTime::restart() + m_offset; | |
m_paused = false; | |
m_offset = 0; | |
return retVal; | |
} | |
void start() | |
{ | |
m_paused = false; | |
QTime::start(); | |
} | |
bool isPaused() | |
{ | |
return m_paused; | |
} | |
void startAt(int ms) | |
{ | |
m_offset = ms; | |
this->start(); | |
} | |
void setOffset(int ms) | |
{ | |
m_offset = ms; | |
} | |
void pause() | |
{ | |
m_offset = this->elapsed(); | |
m_paused = true; | |
} | |
void resume() | |
{ | |
startAt(m_offset); | |
m_paused = false; | |
} | |
QString toString(const QString & format) const | |
{ | |
int ms = this->elapsed() % 1000; | |
int secs = this->elapsed() / 1000; | |
int mins = (secs / 60) % 60; | |
int hours = (secs / 3600); | |
secs = secs % 60; | |
QString f = format; | |
if(hours > 0 && !format.toLower().contains("h")) | |
f.prepend("h:"); | |
QTime timeString(hours, mins, secs, ms); | |
return timeString.toString(f); | |
} | |
private: | |
bool m_paused; | |
int m_offset; | |
}; | |
#endif // MYTIME_H |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Example usage | |
#include "mytime.h" | |
// in your header file | |
MyTime m_stopwatch; | |
// in your code | |
m_stopwatch.start(); | |
m_stopwatch.restart(); | |
// call from pauseButton | |
m_stopwatch.pause(); | |
// call from resumeButton or from playButton | |
m_stopwatch.resume(); | |
// call in your updateTimerLabel slot | |
m_stopwatch.toString("mm:ss.zzz"); | |
// or | |
m_stopwatch.toString("mm:ss"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment