How to display the function time in QLabel so that the time is constantly updated: Before that, do this:

 QTime myTimer; // в начале функции засекаем время int Milliseconds = myTimer.elapsed(); // в конце функции замеряем время ее работы. emit(updateWorkTime(Milliseconds)); // передаем сигнал в слот другой функции // В другой функции реализовываю в слоте отображение в метке void MainWindow::updateWorkTime(int time) { calculationControl->ui->label->setText(QString("%1").arg(time)); } 

However, only the end time of the function will be displayed here. And how to make the displayed time accumulate and update right along the course of the measured function?

  • one
    Although emit is just an empty macro, but it’s customary to write: emit updateWorkTime(Milliseconds); - Alexander

4 answers 4

For example:

 QString uptimeToString(int ms) { // Без оптимизации, для понимания. const int days = ms / 60 / 60 / 24; const int hours = (ms / 60 / 60) % 24; const int minutes = (ms / 60) % 60; const int seconds = ms % 60; // В аргументах символ '0' будет подставлен к цифре, // если число от 0 до 9. const QString str = QString("%1 %2:%3:%4") .arg(days) .arg(hours,2,10,'0') .arg(minutes,2,10,'0') .arg(seconds,2,10,'0'); return str; } void MainWindow::updateWorkTime(int time) { calculationControl->ui->label->setText(uptimeToString(time)); } 
  • QTime, QDate, QDateTime types have a toString method in which you can set the output format, and you don’t need to reinvent such bikes. - Alexander
  • @ Alexander, it always touched this desire of individuals to kick a neighbor with or without. Uzbey. Not always something is done just like that. - alexis031182
  • post added, please see. brought 4 files - Disastricks
  • one
    @DavidRise, you have already written a comment under the answer of Alexander. He will receive a notification about this. And better delete your answer, and place the code directly in the question. - alexis031182 pm

mainwindow.h

 #pragma once #include <QMainWindow> #include <QTime> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); void timerEvent(QTimerEvent *); private: Ui::MainWindow *ui; QTime m_startTime; void updateTime(int _ms); }; 

mainwindow.cpp

 #include "mainwindow.h" #include "ui_mainwindow.h" #include <QTime> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); m_startTime = QTime::currentTime(); updateTime(0); startTimer(1000); } MainWindow::~MainWindow() { delete ui; } void MainWindow::updateTime(int _ms) { QTime time = QTime(0,0,0).addMSecs(_ms); ui->label->setText(time.toString("hh:mm:ss")); } void MainWindow::timerEvent(QTimerEvent *) { int diffMs = m_startTime.msecsTo(QTime::currentTime()); updateTime(diffMs); } 
  • At the moment, you need to pass the time the function is running in the stream to another widget to which we access the mainWindow sketch of the function cited below. - Disastricks 3:32 pm

At the moment, you need to pass the time of the function in the stream to another widget to which we are accessing the mainWindow sketch of the function cited below. From thread.cpp to main stream window

  1. thread.h

     #ifndef THREAD_H #define THREAD_H #include <QThread> #include <QTime> #include <QTimer> #include <global.h> #include <lbd_manager.h> #include <ballistic.h> class Thread : public QThread { Q_OBJECT public: explicit Thread(manager_lbd::ManagerLbd * lbd, Ballistic * ballisticCalc, QObject *parent = 0); int IDPLidThread; bool closeDialog; protected: void run(); signals: void sendMessageGuiKA(int); void sendMessageGuiZRV(int); void sendCloseGui(bool); void sendTimeCalculation(int); private: manager_lbd::ManagerLbd * dbManager; Ballistic * ballistic; }; #endif // THREAD_H 
  2. thread.cpp

     #include "thread.h" Thread::Thread(manager_lbd::ManagerLbd * lbd, Ballistic * ballisticCalc, QObject *parent) : QThread(parent) { dbManager = lbd; ballistic = ballisticCalc; } void Thread::run() { mAssert(ballistic); mAssert(dbManager); // замеряем вначале QTime myTimer; myTimer.start(); // // ТУТ большой расчёт с циклами и тд время которого нужно замерять. // который нужно выводить в label который находится mainWindow в поле класа calculationControl->ui->label выводить постоянно каждую секунду и милисекунды с обновлением label // // время конца расчёта передаем в MainWindow int nMilliseconds = myTimer.elapsed(); emit(sendTimeCalculation(nMilliseconds)); // передаем сигнал, что расчёт закончен, а значит пора закрыть окно. closeDialog = true; emit(sendCloseGui(closeDialog)); } 
  3. mainwindow.h

     #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QPushButton> #include "calcprogressdialog.h" #include "ballistic.h" #include "thread.h" // Менеджеры соединения с БД #include "lbd_manager.h" // Глобальные настройки и параметры #include "global.h" namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public slots: void runCalculation(); void reciveSendGuiKa(int Ka); void reciveSendGuiZrv(int Zrv); void CancelThread(); void reciveTimeCalculation(int time); private: manager_lbd::ManagerLbd *dbManager; CalcProgressDialog *calculationControl; Ballistic *ballistic; Thread *thread; Ui::MainWindow *ui; }; #endif // MAINWINDOW_H 
  4. mainwindow.cpp

     #include <QHBoxLayout> #include <QMessageBox> #include <QComboBox> #include <QGroupBox> #include <QTreeWidget> #include "mainwindow.h" #include "ui_mainwindow.h" // TODO: Неправильное решение, переделать! #include "ui_planeditwidget.h" #include "ui_calculationdata.h" #include "ui_calcprogressdialog.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); dbManager = new manager_lbd::ManagerLbd(this); calculationControl = new CalcProgressDialog(this); ballistic = new Ballistic(this); thread = new Thread(dbManager,ballistic); // Запуск расчёта connect(this->planEditWidget->ui->pushButton_toCalculation, SIGNAL(pressed()), this, SLOT(runCalculation())); // Отмена расчёта connect(calculationControl->ui->pushButton_cancel,SIGNAL(clicked()), this, SLOT(CancelThread())); } MainWindow::~MainWindow() { delete ui; } void MainWindow::reciveSendGuiKa(int Ka) { // Получаем КА и по одному отдаём их в метод расчёта calculationControl->ui->label->setText("Расчёт интервалов прохождения РЦР..."); calculationControl->ui->progressBar->setValue(0); calculationControl->ui->progressBar->setValue(calculationControl->ui->progressBar->value()+Ka); qDebug() << "testGuiKA" << Ka; } void MainWindow::reciveSendGuiZrv(int Zrv) { // Получаем КА и по одному отдаём их в метод расчёта calculationControl->ui->label->setText("Расчёт ЗРВ..."); calculationControl->ui->progressBar->setValue(0); calculationControl->ui->progressBar->setValue(calculationControl->ui->progressBar->value()+Zrv); qDebug() << "testGuiZrv" << Zrv; } void MainWindow::CancelThread() { // TODO: нужно закрывать окно при нажатии в интерфейсе кнопки ОТМЕНА (пока не работает) calculationControl->close(); if(thread->isRunning()) { thread->quit(); thread->wait(); thread->deleteLater(); } } void MainWindow::reciveCloseGui(bool closeDialog) { if (closeDialog == true) { calculationControl->close(); } } void MainWindow::reciveTimeCalculation(int time) { calculationControl->ui->label_old->update(); calculationControl->ui->label_old->setText(QString("%1").arg(time)); calculationControl->ui->label_old->update(); qDebug() << time; } // Запуск расчёта void MainWindow::runCalculation() { calculationControl->show(); connect(thread, SIGNAL(sendMessageGuiKA(int)), this, SLOT(reciveSendGuiKa(int))); connect(thread, SIGNAL(sendMessageGuiZRV(int)), this, SLOT(reciveSendGuiZrv(int))); connect(thread, SIGNAL(sendCloseGui(bool)), this, SLOT(reciveCloseGui(bool))); connect(thread, SIGNAL(sendTimeCalculation(int)), this, SLOT(reciveTimeCalculation(int))); // connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); thread->start(QThread::HighestPriority); qDebug() << "test1"; //calculationControl->close(); //loadAllIDPl(); } 

    To measure the execution time inside the calculation function and constantly spitting with signals about the current time is not optimal. It is more correct to inherit the widget from QLabel, in which when you call the start() slot start() timer will start with the time update. At the end of the calculation, stop the timer and display the time received from the calculation function. Something like this:

    TimeLabel.cpp

     #include "timelabel.h" TimeLabel::TimeLabel(QWidget *parent) : QLabel(parent) { } void TimeLabel::timerEvent(QTimerEvent *e) { setText(QTime(0,0).addMSecs(time.elapsed()).toString("m:ss.zzz")); //эту конструкцию лучше обернуть в отдельную функцию и сделать нормальный выбор формата вывода } void TimeLabel::start() { //TODO проверить, не запущен ли уже таймер, отреагировать time.restart(); timerID = startTimer(100); //запоминаем идентификатор запущенного таймера чтобы потом можно было его прибить } void TimeLabel::stop(int ms) //сюда можно передать время работы функции и оно будет выведено в качестве текста { killTimer(timerID); if (ms > 0) setText(QTime(0,0).addMSecs(ms).toString("m:ss.zzz")); } 

    TimeLabel.h

     #ifndef TIMELABEL_H #define TIMELABEL_H #include <QLabel> #include <QTimer> #include <QTime> class TimeLabel : public QLabel { Q_OBJECT public: explicit TimeLabel(QWidget *parent = 0); protected: void timerEvent(QTimerEvent *e); private: int timerID; QTime time; signals: public slots: void start(); void stop(int ms = 0); }; #endif // TIMELABEL_H 

    With this approach, such labels can be crammed into a form at least a hundred and monitor the execution time of anything. Before starting the calculation, call ui->label->start() , after the end, call (by signal, or directly) stop , passing the runtime function, or clear the text, if necessary.