Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pad a QString with spaces?

Tags:

c++

qt

qt4

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.

like image 807
Wes Avatar asked Nov 09 '11 17:11

Wes


2 Answers

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

like image 111
HostileFork says dont trust SE Avatar answered Sep 20 '22 07:09

HostileFork says dont trust SE


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"

like image 35
UmNyobe Avatar answered Sep 19 '22 07:09

UmNyobe