Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use QStringLiteral?

Tags:

c++

qt

qml

I recently started with QML and I tried to follow this example. The video goes over how to create a C++ model that can be shown in your QML application.

In the data member function of the model, a switch is used and the string that will be displayed in QML is returned in a QVariant but the tutorial also uses an additional QStringLiteral as you can see in the code below.

QVariant ToDoModel::data(const QModelIndex &index, int role) const
{
  if (!index.isValid())
    return QVariant();

  // FIXME: Implement me!
  switch (role)
  {
  case DoneRole:
    return QVariant(false);
  case DescriptionRole:
    return QVariant(QStringLiteral("Test description"));
  }
  return QVariant();
}

I tried this same piece of code without the QStringLiteral and it worked just fine, so what is the purpose of the QStringLiteral?

like image 472
LinG Avatar asked Dec 28 '17 18:12

LinG


1 Answers

What is the purpose of the QStringLiteral?

QString is an interesting string class able to manipulate with both statically and dynamically allocated character strings. The dynamic allocation is more expensive in both code size and performance terms but more flexible and usually practical. Anyway, for when you only need a string once and that is not going to change Qt has a macros QStringLiteral that allocates the character string statically and assigns it as buffer to QString typed object. Unless that QString object assigned with new string the existing buffer is used.

#define QT_UNICODE_LITERAL(str) QT_UNICODE_LITERAL_II(str)
#define QStringLiteral(str) \
    ([]() Q_DECL_NOEXCEPT -> QString { \
        enum { Size = sizeof(QT_UNICODE_LITERAL(str))/2 - 1 }; \
        static const QStaticStringData<Size> qstring_literal = { \
            Q_STATIC_STRING_DATA_HEADER_INITIALIZER(Size), \
            QT_UNICODE_LITERAL(str) }; \
        QStringDataPtr holder = { qstring_literal.data_ptr() }; \
        const QString qstring_literal_temp(holder); \
        return qstring_literal_temp; \
    }()) \
    /**/
like image 135
Alexander V Avatar answered Oct 19 '22 00:10

Alexander V