Qt Code:
  1. class StopWatch : public QWidget
  2. {
  3. Q_OBJECT
  4. public:
  5. explicit StopWatch(QWidget * parent = 0)
  6. : QWidget(parent)
  7. , mRunning(false)
  8. , mStartTime()
  9. , mLabel(new QLabel("0:0:0:0"))
  10. {
  11. QHBoxLayout * hBoxLayout = new QHBoxLayout(this);
  12. QPushButton * startButton = new QPushButton("Start");
  13. QPushButton * stopButton = new QPushButton("Stop");
  14.  
  15. hBoxLayout->addWidget(startButton);
  16. hBoxLayout->addWidget(stopButton);
  17. hBoxLayout->addWidget(mLabel);
  18.  
  19. connect(startButton, SIGNAL(clicked()), SLOT(start()));
  20. connect(stopButton, SIGNAL(clicked()), SLOT(stop()));
  21.  
  22. startTimer(0);
  23. }
  24.  
  25. public slots:
  26. void start(void)
  27. {
  28. mStartTime = QDateTime::currentDateTime();
  29. mRunning = true;
  30. }
  31.  
  32. void stop(void)
  33. {
  34. mRunning = false;
  35. }
  36.  
  37. protected:
  38. void timerEvent(QTimerEvent *)
  39. {
  40. if(mRunning)
  41. {
  42. qint64 ms = mStartTime.msecsTo(QDateTime::currentDateTime());
  43. int h = ms / 1000 / 60 / 60;
  44. int m = (ms / 1000 / 60) - (h * 60);
  45. int s = (ms / 1000) - (m * 60);
  46. ms = ms - (s * 1000);
  47. QString diff = QString("%1:%2:%3:%4").arg(h).arg(m).arg(s).arg(ms);
  48. mLabel->setText(diff);
  49. }
  50. }
  51.  
  52. private:
  53. bool mRunning;
  54. QDateTime mStartTime;
  55. QLabel * mLabel;
  56. };
To copy to clipboard, switch view to plain text mode