Common Qt Classes

Most Qt classes are derived from the QObject class. It encapsulates the central concepts of Qt. But there are many more classes in the framework. Before we continue looking at QML and how to extend it, we will look at some basic Qt classes that are useful to know about.

The code examples shown in this section are written using the Qt Test library. This way, we can ensure that the code works, without constructing entire programs around it. The QVERIFY and QCOMPARE functions from the test library to assert a certain condition. We will use {} scopes to avoid name collisions. Don’t let this confuse you.

QString

In general, text handling in Qt is Unicode based. For this, you use the QString class. It comes with a variety of great functions which you would expect from a modern framework. For 8-bit data, you would use normally the QByteArray class and for ASCII identifiers the QLatin1String to preserve memory. For a list of strings you can use a QList<QString> or simply the QStringList class (which is derived from QList<QString>).

Below are some examples of how to use the QString class. QString can be created on the stack but it stores its data on the heap. Also when assigning one string to another, the data will not be copied - only a reference to the data. So this is really cheap and lets the developer concentrate on the code and not on the memory handling. QString uses reference counters to know when the data can be safely deleted. This feature is called Implicit SharingCommon Qt Classes - 图1 (opens new window) and it is used in many Qt classes.

  1. QString data("A,B,C,D"); // create a simple string
  2. // split it into parts
  3. QStringList list = data.split(",");
  4. // create a new string out of the parts
  5. QString out = list.join(",");
  6. // verify both are the same
  7. QVERIFY(data == out);
  8. // change the first character to upper case
  9. QVERIFY(QString("A") == out[0].toUpper());

Below you can see how to convert a number to a string and back. There are also conversion functions for float or double and other types. Just look for the function in the Qt documentation used here and you will find the others.

  1. // create some variables
  2. int v = 10;
  3. int base = 10;
  4. // convert an int to a string
  5. QString a = QString::number(v, base);
  6. // and back using and sets ok to true on success
  7. bool ok(false);
  8. int v2 = a.toInt(&ok, base);
  9. // verify our results
  10. QVERIFY(ok == true);
  11. QVERIFY(v = v2);

Often in a text, you need to have parameterized text. One option could be to use QString("Hello" + name) but a more flexible method is the arg marker approach. It preserves the order also during translation when the order might change.

  1. // create a name
  2. QString name("Joe");
  3. // get the day of the week as string
  4. QString weekday = QDate::currentDate().toString("dddd");
  5. // format a text using paramters (%1, %2)
  6. QString hello = QString("Hello %1. Today is %2.").arg(name).arg(weekday);
  7. // This worked on Monday. Promise!
  8. if(Qt::Monday == QDate::currentDate().dayOfWeek()) {
  9. QCOMPARE(QString("Hello Joe. Today is Monday."), hello);
  10. } else {
  11. QVERIFY(QString("Hello Joe. Today is Monday.") != hello);
  12. }

Sometimes you want to use Unicode characters directly in your code. For this, you need to remember how to mark them for the QChar and QString classes.

  1. // Create a unicode character using the unicode for smile :-)
  2. QChar smile(0x263A);
  3. // you should see a :-) on you console
  4. qDebug() << smile;
  5. // Use a unicode in a string
  6. QChar smile2 = QString("\u263A").at(0);
  7. QVERIFY(smile == smile2);
  8. // Create 12 smiles in a vector
  9. QVector<QChar> smilies(12);
  10. smilies.fill(smile);
  11. // Can you see the smiles
  12. qDebug() << smilies;

This gives you some examples of how to easily treat Unicode aware text in Qt. For non-Unicode, the QByteArray class also has many helper functions for conversion. Please read the Qt documentation for QString as it contains tons of good examples.

Sequential Containers

A list, queue, vector or linked-list is a sequential container. The mostly used sequential container is the QList class. It is a template based class and needs to be initialized with a type. It is also implicit shared and stores the data internally on the heap. All container classes should be created on the stack. Normally you never want to use new QList<T>(), which means never use new with a container.

The QList is as versatile as the QString class and offers a great API to explore your data. Below is a small example of how to use and iterate over a list using some new C++ 11 features.

  1. // Create a simple list of ints using the new C++11 initialization
  2. // for this you need to add "CONFIG += c++11" to your pro file.
  3. QList<int> list{1,2};
  4. // append another int
  5. list << 3;
  6. // We are using scopes to avoid variable name clashes
  7. { // iterate through list using Qt for each
  8. int sum(0);
  9. foreach (int v, list) {
  10. sum += v;
  11. }
  12. QVERIFY(sum == 6);
  13. }
  14. { // iterate through list using C++ 11 range based loop
  15. int sum = 0;
  16. for(int v : list) {
  17. sum+= v;
  18. }
  19. QVERIFY(sum == 6);
  20. }
  21. { // iterate through list using JAVA style iterators
  22. int sum = 0;
  23. QListIterator<int> i(list);
  24. while (i.hasNext()) {
  25. sum += i.next();
  26. }
  27. QVERIFY(sum == 6);
  28. }
  29. { // iterate through list using STL style iterator
  30. int sum = 0;
  31. QList<int>::iterator i;
  32. for (i = list.begin(); i != list.end(); ++i) {
  33. sum += *i;
  34. }
  35. QVERIFY(sum == 6);
  36. }
  37. // using std::sort with mutable iterator using C++11
  38. // list will be sorted in descending order
  39. std::sort(list.begin(), list.end(), [](int a, int b) { return a > b; });
  40. QVERIFY(list == QList<int>({3,2,1}));
  41. int value = 3;
  42. { // using std::find with const iterator
  43. QList<int>::const_iterator result = std::find(list.constBegin(), list.constEnd(), value);
  44. QVERIFY(*result == value);
  45. }
  46. { // using std::find using C++ lambda and C++ 11 auto variable
  47. auto result = std::find_if(list.constBegin(), list.constBegin(), [value](int v) { return v == value; });
  48. QVERIFY(*result == value);
  49. }

Associative Containers

A map, a dictionary, or a set are examples of associative containers. They store a value using a key. They are known for their fast lookup. We demonstrate the use of the most used associative container the QHash also demonstrating some new C++ 11 features.

  1. QHash<QString, int> hash({{"b",2},{"c",3},{"a",1}});
  2. qDebug() << hash.keys(); // a,b,c - unordered
  3. qDebug() << hash.values(); // 1,2,3 - unordered but same as order as keys
  4. QVERIFY(hash["a"] == 1);
  5. QVERIFY(hash.value("a") == 1);
  6. QVERIFY(hash.contains("c") == true);
  7. { // JAVA iterator
  8. int sum =0;
  9. QHashIterator<QString, int> i(hash);
  10. while (i.hasNext()) {
  11. i.next();
  12. sum+= i.value();
  13. qDebug() << i.key() << " = " << i.value();
  14. }
  15. QVERIFY(sum == 6);
  16. }
  17. { // STL iterator
  18. int sum = 0;
  19. QHash<QString, int>::const_iterator i = hash.constBegin();
  20. while (i != hash.constEnd()) {
  21. sum += i.value();
  22. qDebug() << i.key() << " = " << i.value();
  23. i++;
  24. }
  25. QVERIFY(sum == 6);
  26. }
  27. hash.insert("d", 4);
  28. QVERIFY(hash.contains("d") == true);
  29. hash.remove("d");
  30. QVERIFY(hash.contains("d") == false);
  31. { // hash find not successfull
  32. QHash<QString, int>::const_iterator i = hash.find("e");
  33. QVERIFY(i == hash.end());
  34. }
  35. { // hash find successfull
  36. QHash<QString, int>::const_iterator i = hash.find("c");
  37. while (i != hash.end()) {
  38. qDebug() << i.value() << " = " << i.key();
  39. i++;
  40. }
  41. }
  42. // QMap
  43. QMap<QString, int> map({{"b",2},{"c",2},{"a",1}});
  44. qDebug() << map.keys(); // a,b,c - ordered ascending
  45. QVERIFY(map["a"] == 1);
  46. QVERIFY(map.value("a") == 1);
  47. QVERIFY(map.contains("c") == true);
  48. // JAVA and STL iterator work same as QHash

File IO

It is often required to read and write from files. QFile is actually a QObject but in most cases, it is created on the stack. QFile contains signals to inform the user when data can be read. This allows reading chunks of data asynchronously until the whole file is read. For convenience, it also allows reading data in blocking mode. This should only be used for smaller amounts of data and not large files. Luckily we only use small amounts of data in these examples.

Besides reading raw data from a file into a QByteArray you can also read data types using the QDataStream and Unicode string using the QTextStream. We will show you how.

  1. QStringList data({"a", "b", "c"});
  2. { // write binary files
  3. QFile file("out.bin");
  4. if(file.open(QIODevice::WriteOnly)) {
  5. QDataStream stream(&file);
  6. stream << data;
  7. }
  8. }
  9. { // read binary file
  10. QFile file("out.bin");
  11. if(file.open(QIODevice::ReadOnly)) {
  12. QDataStream stream(&file);
  13. QStringList data2;
  14. stream >> data2;
  15. QCOMPARE(data, data2);
  16. }
  17. }
  18. { // write text file
  19. QFile file("out.txt");
  20. if(file.open(QIODevice::WriteOnly)) {
  21. QTextStream stream(&file);
  22. QString sdata = data.join(",");
  23. stream << sdata;
  24. }
  25. }
  26. { // read text file
  27. QFile file("out.txt");
  28. if(file.open(QIODevice::ReadOnly)) {
  29. QTextStream stream(&file);
  30. QStringList data2;
  31. QString sdata;
  32. stream >> sdata;
  33. data2 = sdata.split(",");
  34. QCOMPARE(data, data2);
  35. }
  36. }

More Classes

Qt is a rich application framework. As such it has thousands of classes. It takes some time to get used to all of these classes and how to use them. Luckily Qt has a very good documentation with many useful examples includes. Most of the time you search for a class and the most common use cases are already provided as snippets. Which means you just copy and adapt these snippets. Also, Qt’s examples in the Qt source code are a great help. Make sure you have them available and searchable to make your life more productive. Do not waste time. The Qt community is always helpful. When you ask, it is very helpful to ask exact questions and provide a simple example which displays your needs. This will drastically improve the response time of others. So invest a little bit of time to make the life of others who want to help you easier 😃.

Here some classes whose documentation the author thinks are a must read:

That should be enough for the beginning.