Wes
Wes

Reputation: 5067

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.

Upvotes: 15

Views: 26414

Answers (2)

UmNyobe
UmNyobe

Reputation: 22920

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"

Upvotes: 4

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.)

Upvotes: 29

Related Questions