Threading is the main concept which every programmer needs to know to write a good program so in this tutorial we will build a stopwatch using threading. Please remember that this tutorial is meant to teach you the concept of threading and not how to build the stopwatch. Actual watches are made in a more efficient way than this.
Overview of task: The stopwatch will display hour, minutes and seconds. It will have a start and a stop push button. Once the clock is stopped and started again it will count from the beginning.
Prerequisites: Basic knowledge of QT class QThread
- Create a new Qt GUI project with dialog.
- Create a layout for our clock. You can use LCD numbers widgets to make it look like a real watch. You will require 3 LCD number widget for hours, minutes and seconds respectively. Two push buttons one for start and one for stop.
- Now create a simple new C++ class with Qthread inherited.
- In this class, we will a constructor with two arguments QObject *parent and int count. In addition a private data member count and a signal countChanges(int). We will use this count variable to increment our time.
- In the constructor of the Counter class use member initialiser Qthread(parent) and also initialize our counter variable.
- Now we will override the method run() of QThread which is inherited. Inside it, we will have a simple for loop. for loop will start counting from 0 we will increment it by one and will not have any condition(will become infinite loop). Inside this loop, we will emit countChanges(i) signal. Then we will call sleep(count), this is also inside loop.
- Now inside our dialog class, we will have 3 pointer object of Counter class hour, min and sec. Initiate these objects with the parent object and the frequency of update in second(for hour update frequency will be 3600, for minute 60 and for second 1).
- Now connect SIGNAL countChanges with SLOT display() of LCD widget for all three Counter objects to its corresponding LCD widget.
- Create slot for start button clicked. Inside it call the start() method for each counter object.
- Create slot for stop button clicked. Inside it call the terminate() method for each counter object.
- Link to your repository
- Video of your working stopwatch.
Try some experiment: See what happens if we change sleep() method with wait().
If you can not understand any part or solve any problem contact mentor they are always happy to help.