mercredi 6 mai 2015

Accessing Qt widget thread safe

I use a QPlainTextEdit to display some text. This text will be modified (append) in another thread than the ui(main) thread with sending a signal to the widget

connect(this, SIGNAL(addText(QString)), mUi->plainTextEditLog, SLOT(appendPlainText(QString)));

...
emit addText(QString::fromStdString(someString));
...

another thread is reading the text of this PlainTextEdit and writes it to a file

QFile file(fileName);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) {
    return;
}
file.write(mUi->plainTextEditLog->toPlainText().toUtf8());
file.close();

As far as i know the Qt widgets aren't thread safe. I thought about a mutex to lock the writing signal emit, but this wont lock it really because it is only sending a signal asynchronously.

The reason why i use signals is that the writing method can be called from more than one thread and a mutex didn't help in this case but signals do perfectly.

The second thought was to store the text also in my class and lock the string with mutual exclusion. But i am not sure if this is very efficient because there is not only the plaintextedit that has to be modified but also the string as a copy.

Aucun commentaire:

Enregistrer un commentaire