Paint to pixmap in thread
-
I encountered a problem drawing to a pixmap in a thread:
// run in a thread QStyleOptionButton opt; QPixmap pixmap(10, 10); QPainter painter(&pixmap); const QStyle* style = QApplication::style(); style->drawPrimitive(QStyle::PE_IndicatorCheckBox, &opt, &painter);With this code, the style of the UI on the main thread broke from time to time! Debugging showed that globalStyleSheetStyle inside qstylesheetstyle.cpp was never resetted to null. The static variable value was apparently messed-up by thread-unsafe usage (two concurrent drawing calls on different threads). Note that the problem is not the style of the application being used in two threads, using two different styles could cause the same problem because all instances are using the same static globalStyleSheetStyle.
Are all drawing operations intentionally limited to the main thread or are the conditions more relaxed? I could not find threading information in the documentation of QStyle or QPainter. Sorry for the fuzzy question, I'd like to know better what is safe to do and what not, and if there are other apparently independent classes in Qt that share static resources. Thanks.
-
It's ok to use a worker thread to paint on QImage, QPrinter and QPicture, but painting this way on either QPixmap or QWidget is not supported. It's not explicitly stated, but basically pretty much everything related to widgets (so styles and stylesheets too) can only be accessed on the main thread (unless you explicitly synchronize).
-
Very clear, thanks a lot. I did not know that QPixmap is so tightly close to the widgets.
@igor_fa1 said:
I did not know that QPixmap is so tightly close to the widgets
It's not. That's why it's mentioned separately. But they both are meant to be used on the main thread. QPixmap is optimized for displaying while QImage is a class for data manipulation and I/O.