QLabel::setText() from a secondary thread



  • Dear Qt users,
    I have always thought that it was not possible to update GUI QWidgets from any other thread than the main one.
    However I accidentally (I swear!) wrote a piece of code that calls QLabel::setText() from a secondary thread.
    And it works. How do you explain this?



  • It is perfectly possible that non-threadsafe code works in multithreaded environments, however it is not guaranteed to do so. That's why you shouldn't modify any widgets outside the main thread - it may work in rare occasions, it might even work in most occasions, but it does not work in all occasions.



  • Ok but usually in that case your are warned by an error message: "Cannot send events to objects owned by a different thread"



  • While it would be possible to check for which thread is calling a function in debug builds, it would be too much overhead for release builds IMO. The ground rule is that if a method is not marked as being thread safe, it is not. For setting text, it will work unless the main thread is accessing the text at the same time. It will definitely crash once you ship the program to the client, says Murphy's law :-)


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.