3

I spawn a secondary thread to perform some tedious job, pass the destination QTextBrowser to it, and hope it can output runtime messages by insertHtml() to QTextBrowser. Sometimes it works, but eventually crashes the application.

Originally, I use print(), and redirect stdout and sderr to the QTextBrowser. It works well. Because I need the rich text capability so I discard this method.

From here or here or here, I noticed that it might not be legit.

In GUI applications, the main thread is also called the GUI thread because it's the only thread that is allowed to perform GUI-related operations.

As mentioned, each program has one thread when it is started. This thread is called the "main thread" (also known as the "GUI thread" in Qt applications). The Qt GUI must run in this thread. All widgets and several related classes, for example QPixmap, don't work in secondary thread

I'm not sure about it. I need someone to confirm this point. And may suggest a regular way to implement it.

Community
  • 1
  • 1
minion
  • 561
  • 4
  • 17

1 Answers1

6

In general, GUI classes (widgets + some others) should only be used in the main thread, as stated in the docs you quoted in your question. So yes, don't go messing about with QTextBrowser in a new thread.

The docs also state: Qt classes are only documented as thread-safe if they are intended to be used by multiple threads. If a function is not marked as thread-safe or reentrant, it should not be used from different threads. If a class is not marked as thread-safe or reentrant then a specific instance of that class should not be accessed from different threads.

But you should note that insertHtml is a slot. So you can easily connect a signal to it that you emit in a different thread (just don't make it explicitly a direct connection).

thuga
  • 12,601
  • 42
  • 52