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?
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; \
}()) \
/**/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With