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.
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
.)
You can also use the QString::arg() overload which take a field width parameter. The field width value is the total number of desired characters, not the padding size. You need to use a negative field width value for left padding, a positive for right padding
QString QString::arg(const QString & a,
int fieldWidth = 0, const QChar & fillChar = QLatin1Char( ' ' ))
Most useful in a printf
style formatting, for instance.
QString("%1: %2 - %3").arg("a", -4).arg(2).arg(10);
gives "a :2 - 10"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With