What is the proper way to draw thousands of rects
in QT (around 100,000 or more)?
I tried:
- Simple with
paintEvent()
ofQWidget
. - Drawing objects to
QImage
then this image toQWidget
. - Using
QGraphicsScene
(maybe I didn't use it properly, I just addedrects
to scene)
Every time drawing was really slow and I don't have more ideas on how to do this (maybe with opengl/directx but this doesn't sound like a good idea). I know that there exist applications that do that so there should be some way.
EDIT:
I wonder how drawRects()
work? Is there a chance that filling some uchar*
array and passing it to QImage
will be better?
Solution which I found:
Create array of
uint32_t
which can contain all pixels ofwidget
, fill it usingmemcpy()
. CreateQImage
with this array and usedrawImage()
to show it. It can have some optimization like (for profiler) mergingrects
that are continues ( start time second is equal to end of first ). Don't drawrects
that are out of time bounds. Maybe skip too smallrects
. For drawing things like text, tool tips you can still useQt
functions. For alpha blending in simplest case you can just take existing values, blend them in loop and write blended values or maybe useSIMD
for this.Of course for more complex shapes it will get harder to draw but still, I think, it will be faster than using
Qt
functions.The first trick is to do the drawing in a separate thread onto a
QImage
, then pass that into the main thread. This won't make it quicker, but it'll make it not block the GUI thread.As a separate concern, you can then split the drawing across multiple parallel jobs, by clipping each job's painter to a sub-area of the shared image, and noting that fully clipped rectangle draws are no-ops, and partially clipped ones will only fill the pixels they affect.