I have a function that is called by a separate thread and the thread is separated:

std::thread thr(IncrementTime:: incTime); thr.detach(); 

This function is an infinite loop.

The task is to change the label of the form (Widget) after each passing of the cycle.

Parts of the code:

IncrementTime.h

 #ifndef INCREMENTTIME_H #define INCREMENTTIME_H class IncrementTime { public: static void incTime(); }; #endif // INCREMENTTIME_H 

IncrementTime.cpp

 #include "incrementtime.h" #include "global_objects.h" #include <windows.h> #include "widget.h" void IncrementTime::incTime(){ Widget widg; while(1){ sec++; if(sec == 60){ sec = 0; } //тут выпадает ошибка widg.smena(); //Cannot create children for a parent that is in a Sleep(1000); //different thread } } 

widget.cpp

 #include "widget.h" #include "ui_widget.h" #include "global_objects.h" Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) { ui->setupUi(this); } Widget::~Widget() { delete ui; } void Widget::smena(){ ui->label_3->setText(QString::number(sec)); } 

widget.h

 #ifndef WIDGET_H #define WIDGET_H #include <QWidget> namespace Ui { class Widget; } class Widget : public QWidget { Q_OBJECT public: explicit Widget(QWidget *parent = nullptr); ~Widget(); public slots: void smena(); private: Ui::Widget *ui; }; #endif // WIDGET_H 
  • Qt has built-in timers - QTimer . You can start it (specifying a timeout of one second), and call a slot in your widget by a signal from the timer. - vegorov

1 answer 1

You can work with GUI only from the main program thread. In your case, the stream should not change the values ​​on the widget itself, but send a signal to it to change the data so that all changes occur in the main stream. A separate thread is needed, if the calculations require a lot of time and the interface constantly hangs, but if there is nothing else in your incTime (), then it is more logical to use the timer and not bother with the threads.