要复制所有属性,您必须使用metaobject()
,通过这个我们获取属性,我们可以复制它们,如下所示。注意:并非所有属性都可以写入,为此我们使用方法检查isWritable()
:
QQuickItem *copyQQuickItem(QQuickItem *item){
QQuickItem *item_Copy = new QQuickItem;
const QMetaObject *mo = item->metaObject();
for (int i = mo->propertyOffset(); i < mo->propertyCount(); ++i){
if(mo->property(i).isWritable()){
const char* name = mo->property(i).name();
item_Copy->setProperty(name, item->property(name));
}
}
return item_Copy;
}
例子:
QQuickItem * my_item = engine.rootObjects()[0]->findChild<QQuickItem*>("ItemObjectName");
QQuickItem *item_copy = copyQQuickItem(my_item);
const QMetaObject *mo = my_item->metaObject();
for (int i = mo->propertyOffset(); i < mo->propertyCount(); ++i){
if(mo->property(i).isWritable()){
const char* name = mo->property(i).name();
qDebug()<<name<<my_item->property(name)<<item_copy->property(name);
Q_ASSERT(my_item->property(name)==item_copy->property(name));
}
}
输出:
parent QVariant(QQuickItem*, QQuickRootItem(0x55975cfdf520)) QVariant(QQuickItem*, QQuickRootItem(0x55975cfdf520))
x QVariant(double, 0) QVariant(double, 0)
y QVariant(double, 0) QVariant(double, 0)
z QVariant(double, 0) QVariant(double, 0)
width QVariant(double, 100) QVariant(double, 100)
height QVariant(double, 100) QVariant(double, 100)
opacity QVariant(double, 1) QVariant(double, 1)
enabled QVariant(bool, true) QVariant(bool, true)
visible QVariant(bool, true) QVariant(bool, true)
state QVariant(QString, "") QVariant(QString, "")
baselineOffset QVariant(double, 0) QVariant(double, 0)
clip QVariant(bool, false) QVariant(bool, false)
focus QVariant(bool, false) QVariant(bool, false)
activeFocusOnTab QVariant(bool, false) QVariant(bool, false)
rotation QVariant(double, 0) QVariant(double, 0)
scale QVariant(double, 1) QVariant(double, 1)
transformOrigin QVariant(int, 4) QVariant(int, 4)
smooth QVariant(bool, true) QVariant(bool, true)
antialiasing QVariant(bool, false) QVariant(bool, false)
implicitWidth QVariant(double, 0) QVariant(double, 0)
implicitHeight QVariant(double, 0) QVariant(double, 0)