Qml:从c++;一方失效 当我在C++中玩QML属性时,我偶然发现了奇怪的行为。如果属性类型为var,并且我用不同的类型覆盖属性值,则调用析构函数时它将失效。 当您将qml objects属性值覆盖为,即QVariant(QString())值在调用析构函数时失效
例如: 我有一个类Qml:从c++;一方失效 当我在C++中玩QML属性时,我偶然发现了奇怪的行为。如果属性类型为var,并且我用不同的类型覆盖属性值,则调用析构函数时它将失效。 当您将qml objects属性值覆盖为,即QVariant(QString())值在调用析构函数时失效,c++,qt,qml,var,variant,C++,Qt,Qml,Var,Variant,例如: 我有一个类Test,它派生自QObject,并注册为qml类型。我添加了QQmlParserStatus来访问componentComplete()函数 我在qml中创建Test对象,并添加属性foo import QtQuick 2.9 import QtQuick.Window 2.2 import Custom 1.0 Window { visible: true width: 640 height: 480 Test { pro
Test
,它派生自QObject
,并注册为qml类型。我添加了QQmlParserStatus
来访问componentComplete()
函数
我在qml中创建Test
对象,并添加属性foo
import QtQuick 2.9
import QtQuick.Window 2.2
import Custom 1.0
Window {
visible: true
width: 640
height: 480
Test {
property var foo: 123
}
}
这里C++的边是<代码>测试< /Cord>类源:
#ifndef TEST_H
#define TEST_H
#include <QObject>
#include <QQmlApplicationEngine>
#include <QQmlParserStatus>
#include <QMetaProperty>
#include <QDebug>
class Test : public QObject, public QQmlParserStatus
{
Q_OBJECT
public:
explicit Test(QObject *parent = nullptr)
: QObject(parent) {}
~Test() {
const QMetaObject *o = metaObject();
int offset = o->propertyOffset();
int count = o->propertyCount();
for (int i = offset; i < count; ++i) {
QMetaProperty metaPropert = o->property(i);
QVariant val = property(metaPropert.name());
qDebug() << val;
}
}
static void registerTypes() {
qmlRegisterType<Test>("Custom", 1, 0, "Test");
}
protected:
void classBegin() Q_DECL_OVERRIDE {}
void componentComplete() Q_DECL_OVERRIDE {
const QMetaObject *o = metaObject();
int offset = o->propertyOffset();
int count = o->propertyCount();
for (int i = offset; i < count; ++i) {
QMetaProperty metaPropert = o->property(i);
QVariant val = property(metaPropert.name());
qDebug() << val;metaPropert.write(this, QString("test"));
metaPropert.write(this, QString("test"));
qDebug() << property(metaPropert.name());
}
}
};
#endif // TEST_H
我期望得到的是:
QVariant(int, 123)
QVariant(QString, "test")
QVariant(QString, "test")
若属性值是string,我将其覆盖为string,那个么它不会失效
另外,如果我将属性类型从var
更改为variant
属性值不会失效。但据我所知,variant
已经过时,我不应该使用它
我的问题是:为什么财产会失效?这是预期的行为吗?有趣的问题。看起来像只虫子。您是否在Qt bug tracker中创建了记录单?顺便说一句,您能否尝试使用
QQmlProperty::read
/QQmlProperty::write
访问属性?另外,请尝试QObject::setProperty
以确保其正常工作。QQmlProperty::read
/QQmlProperty::write
无效,QObject::setProperty
返回true,但未解决问题。我将创建一个票证。
QVariant(int, 123)
QVariant(QString, "test")
QVariant(QString, "test")