I am thinking of regular expressions, but that is not exactly readable. There are also functions like s.toUpper()
to consider, and probably other things as well.
So what is the best method for capitalising the first letter of words in a QString?
If the QString
is placed in any item that uses QFont
, you can use its setCapitalization
property to change text to title case. Here is an example - my code is very happy to have discovered it.
QFont formatFont = m_formatNameEdit->font();
formatFont.setCapitalization(QFont::Capitalize);
m_formatNameEdit->setFont(formatFont);
Thanks to an answer from Qt Centre Thread: How to capitalize a string
There is an alternative way of doing this which iterates using references to the words and modifies the first character using a QChar reference instead:
QString capitalise_each_word(const QString& sentence)
{
QStringList words = sentence.split(" ", Qt::SkipEmptyParts);
for (QString& word : words)
word.front() = word.front().toUpper();
return words.join(" ");
}
Note that Qt::SkipEmptyParts
is required here (as in the other answers to this question) since the first character of each word is assumed to exist when capitalising. This assumption will not hold with Qt::KeepEmptyParts
(the default).
Exactly the same, but written differently :
QString toCamelCase(const QString& s)
{
QStringList cased;
foreach (QString word, s.split(" ", QString::SkipEmptyParts))cased << word.at(0).toUpper() + word.mid(1);
return cased.join(" ");
}
This uses more memory but is without pointer access (no brackets operator).
Using this example as a reference, you can do something like this: