QString如何使用QVariant::fromValue?

How to use QVariant::fromValue with QString?

我有以下代码:

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

这个不行,QTCreator中报错如下:

...\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)

我不认为我应该使用 Q_DECLARE_METATYPE 作为 QString 因为如果我这样做:

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

它工作正常。

我感兴趣的是如何将 QVariant::fromValue() 与预先声明的 QString 一起使用。

QVariant::fromValue() 需要 QString,而不是指向 QString.

的指针

此外,在堆上分配一个 QString 对象没有多大意义。在幕后,QString 使用写时复制 (COW) 作为优化;无论如何,存储在 QString 中的实际数据将始终在堆上。

data 是指向 QString 的指针,而不是 QString 本身。要使用 QVariant::fromValue() 方法,您必须取消引用指针:

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

这是因为 QString * 不是已注册的元类型(默认情况下)。