Most of the times this will work, painting the text correctly. But sometimes it fails to draw the last char in the string. When it fails, the values for fm.width(str) and l.maximumWidth() are different by 1 pixel (the layout width is larger). If change to

@
line.setLineWidth(fm.width(str)+1);
@

then draws the entire string. Shouldn't the with of the QTextLayout be the same or less than the one provided by QFontMetrics?