xlw12
xlw12

Reputation: 781

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.

Upvotes: 2

Views: 1139

Answers (1)

cppguy
cppguy

Reputation: 3713

In essence, as long as you use an auto or queued connection (see QObject::connect) when connecting a signal from an object that belongs to another thread (see QObject::moveToThread) to a widget (which must belong to the main gui thread), then emitting the signal will be an asynchronous "fire and forget" call. You can also make the call synchronous by specifying that it's a blocking queued connection but I don't recommend it unless you really require it.

The threading model in Qt takes a bit to wrap your head around but you'll grow to love the simplicity signals and slots provide in multithreaded code and how many pieces of code will no longer need to protect their data with mutexes.

Upvotes: 1

Related Questions