Search code examples
c++qtqt4

How do I pad a QString with spaces?


How can I pad a QString with spaces on the end?

For example, I want a QString to be 4 characters in total, and it's only 1 character long. I would like the last 3 to be spaces.


Solution

  • Strangely enough, there's a function for specifically that called QString::leftJustified

    http://doc.qt.io/qt-4.8/qstring.html#leftJustified

    So paddedString = originalString.leftJustified(4, ' '); would do the trick.

    (Note that you can also optionally truncate the string if it's longer than your character limit by passing in a third parameter of true.)