Reputation: 293
A beginner's question but actually I'm stuck. I am not allowed to use "high-level" c++ threading function (nor pthread, nor QThread). However, there are some thread that I should create with winAPI function createThread. And those threads use to change some variables. I want to show these variables every 1 second in a QLineEdit component. So I tried a code like:
stillWorking = true;
while(stillWorking){
ui->editElement->setText(QString::number(getVariableValue()));
qDebug() << 'running!!!'
Sleep(1000);
}
The stillWorking
boolean value is set to false
when some button is clicked. That's how I hope to stop this loop. But, when I execute the code, the editElement
isn't updated and the application stop responding. However, the 'running!!!'
string is well printed in the debug section every second. So, is there any other way to access and show my variables?
Upvotes: 1
Views: 2072
Reputation: 344
You can use any of these two ways;
Fisrt one is explained above from Mat
Second way is if your class derivated from QObject, you can override the timerEvent
class MyObject : public QObject
{
Q_OBJECT
public:
MyObject(QObject *parent = 0);
int timerID;
protected:
void timerEvent(QTimerEvent *event);
};
MyObject::MyObject(QObject *parent)
: QObject(parent)
{
timerID = startTimer(1000); // 1-second timer
}
void MyObject::timerEvent(QTimerEvent *event)
{
ui->editElement->setText(QString::number(getVariableValue()));
this->killTimer(timerID); // you can use here if you plan stop timer
}
in your function your visible widget is updated if while loop is break else your application work but not update any gui widget while process in loop.
Upvotes: 0
Reputation: 206679
You should use a QTimer
, assuming you're allowed to (even if you were allowed to use threads). Doing any sort of blocking on the UI thread will not work, it needs to be released for event processing to work, and reacting to clicks needs event processing.
The Timers page has a bit more info and examples of how to use it. The idea here would be to create a slot that simply does:
ui->editElement->setText(QString::number(getVariableValue()));
and a repeating timer connected to that slot.
(This assumes that getVariableValue()
is properly synchronised and does indeed see the updated value from that other thread.)
Upvotes: 3