Search code examples
qtqwidgetqstringqpainter

How to render QStringView using QPainter?


I'm implementing a custom text layouting engine and I need to render a lot of QStringViews. But QPainter's drawText overloads only accept QStrings. Converting all these QStringViews to QStrings just to draw them is terribly inefficient and kinda defeats the purpose of using string views in the first place.

Is there a way to avoid intantiating many QStrings just to use the drawText functions? Maybe there's a way to create a "fake" QString? Or maybe there is a lower-level (but still cross-platform) text drawing method? Thanks!


Solution

  • I still haven't found a way to use QStringView specifically for this purpose.

    However, I did find a way to create QStrings while avoiding expensive copying.

    QString has a static method named fromRawData that allows to create a QString from pre-existing pointer and length. Using this method, it seems that I was able to avoid copying.

    Here's the description of this method:

    enter image description here

    It worked great for my case, however I must admit I haven't profiled the resulting code and relied on the information from the docs. Please check it for yourself.