How to call .appendPlainText() from non GUI-thread
Hi guys, I've been stuck with this problem for a while now, I keep getting runtime errors when I try to call a
function from the non-main GUI thread, how will I get past this? I'm not sure if I should but I am using a mutex to keep it synchronized with the other threads. Is there another thread-safe(is this the correct term to use?) function I can use? Thanks in advance for any help! Sorry I'm still very new to Qt and I'm not sure if I should use signals and slots...
You can't access GUI related function from secondary thread. However you can use signals and slots for that purpose.
Hope it helps
So, don't call that function. Notice that that function is declared as a slot. That means that you can connect to it, and Qt is nice enough to make that thread safe for you.
So, give your thread a signal that emits a QString, and connect that signal to your QPlainTextEdit::appendPlainText slot. Now, instead of the direct call to appendPlainText, emit your signal instead.
Thank you for all the help! I'm still a noob sorry :P So will I declare a signal and connect it like this?:
@connect(this, SIGNAL(someSignal(QString), plainTextEditPointer, SLOT(appendPlainText(QString)))@
Esssentially, yes, though I usually prefer to do the connection at the other end. I think the thread (worker) should not need to care what happens with the results it produces. They may get logged to file, discarded, send over the network, or in this case displayed in a plain text edit: it should not matter to the code producing the data.
Instead, I'd make the connection at the GUI-side of things, so you'd end up with something like:
connect(m_worker, SIGNAL(newDataAvailable(QString)), m_ui->pteDataView, SLOT(appendPlainText(QString)));
//or, Qt 5 syntax:
The advantage of the second syntax is that it will give you compile-time warnings if the connection is incorrect. The downside is that adding overloads to the signal or slot will break your connection code.
Thank you very much! Finally this worked, again thanks for the help!