How to use QString in Qt
Article Metadata
Tested with
Devices(s): Symbian emulator & creator IDE V4.5
Compatibility
Platform(s): Qt
Article
Keywords: QString
Created: james1980
(31 Dec 2008)
Last edited: hamishwillee
(11 Oct 2012)
This example demonstrates some basic Qt string functions.
Note:Some of images are from qt Creator IDE V4.5 and the code associated with images can also be executed in carbide c++ 2.0
Various Function and Operators
- If you want to append a certain number of identical characters to the string, use operator+=()
The final content of str is "Hello" followed by ten "X": "HelloXXXXXXXXXX".
- Prepends the string Hello to the beginning of str and returns a reference to this string.
QString str = "world";
str.prepend("Hello ");
The content of str is "Hello world".
- Returns a lowercase copy of the string.
The content of lowerCase is "hello". The content of str is still "HELLO", the method QString::toLower() does not modify the string, it returns a lowercase version of the string.
Code snippet using QString
The following example show the use of QString in a graphical application. QLabel is a widget capable of displaying text or images.
#include <QApplication>
#include <QLabel>
#include <QString>
#include <QVBoxLayout>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QString str("world");
QString sizeOfWorld = QString::number(str.size());
// resize the string and removes last two characters
str.resize(3); // str = "wor"
// Add "Hello " at the beginning
str.prepend("Hello "); // str = "Hello wor"
// Add "ld" at the end
str.append("ld"); // str = "Hello world"
// Remove 6 characters at position five, and insert " India" at this position
str.replace(5, 6, " India");
QLabel *label1 = new QLabel(str);
QLabel *label2 = new QLabel(sizeOfWorld);
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(label1);
layout->addWidget(label2);
QWidget window;
window.setLayout(layout);
window.show();
return app.exec();
}
Here is the result of this code on Microsoft Windows:


20 Sep
2009
This article is very good.
It presents some common methods of QString and systematically mixes an example and a small explanation. The final example might be a bit too complicated for a beginner but the comments describe everything so I think it is ok. I like this final example because one can easily play with it in the simulator.
There is one thing I really miss for a introduction to QString: an explanation of the method QString::arg(). This method is very useful, while QString::append() or QString::prepend() are mostly useless in real applications because of internationalization.
This article is still "Reviewer Approved" for me. It is good even without QString::arg().
11 Sep
2009
A string operation is fully described in this article. It’s a good to learn how to perform a particular operation on the string in Qt. at the start the method is described very well.
A small image says everything about the article.