Solved We konw updating widget in thread is not safe, but if i read widget in thread ,is it safe?
-
assume in a thread, ui->label->setText("abc") is not safe, as we know.
but if i just read the text in a thread ,is it safe now?
QThread::run()
{
Mainwindow p = qobject_cast<Mainwindow>(parent);
p->readText();
}and the func is:
QString Mainwindow::readText()
{
QString str = ui->label->text();
return str;
} -
@QtTester said in We konw updating widget in thread is not safe, but if i read widget in thread ,is it safe?:
but if i just read the text in a thread ,is it safe now?
No.
The GUI thread could change the text while your other thread tries to read the text. So your other thread could try to read string data that has already been freed.
-
@JKSH it may not get the right data, but the app should not crash ,right?
-
@QtTester said in We konw updating widget in thread is not safe, but if i read widget in thread ,is it safe?:
@JKSH it may not get the right data, but the app should not crash ,right?
If it tries to read a string that is being destroyed, it can crash.
-
@JKSH In a app lifetime ,the qlabel will be destroyed after the qthread ( or we guarantee that), so i donot think it will crash.
-
@QtTester said in We konw updating widget in thread is not safe, but if i read widget in thread ,is it safe?:
@JKSH In a app lifetime ,the qlabel will be destroyed after the qthread ( or we guarantee that), so i donot think it will crash.
I said the string, not the QLabel.
QLabel::setText() can destroy the old string. So if your GUI thread calls label->setText(...) at the same time that your other thread calls label->text(), bad things can happen.
-
@JKSH Thanks a lot.