I'm making an app on QT with UI. Also, I have a function. I want to display the running time of a function. I also want to pause the stopwatch. Any ideas on how to properly embed a stopwatch in my application? Here is my code:
void SomeFunc()
{
while (1)
{
// Start Timer
// some code
// Stop Timer
// Start Timer2
// some code
// Stop Timer2
}
}
on_push_button()
{
auto futureWatcher = new QFutureWatcher<void>(this);
QObject::connect(futureWatcher, &QFutureWatcher<void>::finished, futureWatcher, &QFutureWatcher<void>::deleteLater);
auto future = QtConcurrent::run( [=]{ PackBytes( file_path, file_name, isProgressBar); });
futureWatcher->setFuture(future);
}
CodePudding user response:
Use QElapsedTimer
for measuring the duration since starting the computation.
Judging from your previous questions on very related topics, you do have a MainWindow
class that contains the on_push_button
function. In that class, declare the QElapsedTimer
member; then start it when your computation starts.
Use a QTimer
to update the GUI element you use for displaying the current duration (only needs to run once a second or so).
Example code:
in your header file:
#include <QElapsedTimer>
#include <QTimer>
//...
class MainWindow
{
// ... other stuff you have
private:
QTimer m_stopwatchUpdate;
QElapsedTimer m_stopwatchElapsed;
};
in your cpp file:
void MainWindow::on_push_button()
{
// ideally do this once only in the constructor of MainWindow:
connect(&m_stopwatchUpdate, &QTimer::timeout, this, [=]{
//.. update GUI elements here...
});
auto futureWatcher = new QFutureWatcher<void>(this);
connect(futureWatcher, &QFutureWatcher<void>::finished, futureWatcher, &QFutureWatcher<void>::deleteLater);
auto future = QtConcurrent::run( [=]{
m_stopwatchElapsed.start();
PackBytes(file_path, file_name, isProgressBar);
});
m_stopwatchUpdate.start(1000);
futureWatcher->setFuture(future);
}