1

I have the following code:

QString* data = new QString("data to QML");
engine.rootContext()->setContextProperty(QStringLiteral("consoleText"), QVariant::fromValue(data));

and this one does not work, the error message in QTCreator is the following:

...\qglobal.h:693: error: static assertion failed: Type is not registered, please use the Q_DECLARE_METATYPE macro to make it known to Qt's meta-object system #define Q_STATIC_ASSERT_X(Condition, Message) static_assert(bool(Condition), Message)

I do no think that I should use Q_DECLARE_METATYPE for QString because if I do something like this:

engine.rootContext()->setContextProperty(QStringLiteral("consoleText"), QVariant::fromValue(QString("data to QML")));

it works fine.

I am interested in that how can I use the QVariant::fromValue() with a pre-declared QString.

Bence Kaulics
  • 7,066
  • 7
  • 33
  • 63

2 Answers2

4

QVariant::fromValue() expects a QString, not a pointer to a QString.

Additionally, allocating a QString object on the heap doesn't make much sense. Under the hood, QString uses copy-on-write (COW) as an optimization; the actual data stored in the QString will always be on the heap anyway.

BaCaRoZzo
  • 7,502
  • 6
  • 51
  • 82
MrEricSir
  • 8,044
  • 4
  • 30
  • 35
1

data is a pointer to a QString, not a QString itself. To use the QVariant::fromValue() method, you must dereference the pointer:

engine.rootContext()->setContextProperty(QStringLiteral("consoleText"), QVariant::fromValue(*data));
                                                                                            ^

This is because a QString * is not a registered meta-type (by default).

owacoder
  • 4,815
  • 20
  • 47