0

我有一个QQuickItem像这样从 C++ 端获取的。

QQuickItem * my_item = qmlEngine->rootObjects()[0]->findChild<QQuickItem*>("ItemObjectName");

my_item是有效的,并且设置了所有属性。

场景
我有2 个窗口需要QQuickItem交替绘制。我想把它渲染my_item到另一个窗口。只要我将父级设置my_item为另一个窗口,这一切都很好

// the_other_window is a QQuickWindow
QQuickWindow * the_other_window;

// here I set parent
my_item->setParentItem(the_other_window->contentItem());

这需要我setParentItem再次回到my_item的原始窗口,否则它在原始窗口上不可见。这是有效的,但给了我不必要的依赖。相反,我正在尝试创建QQuickItem& 的副本并setParentItem对其进行操作。通过这样复制:

QQuickItem * item_copy = new QQuickItem(my_item);

问: 我想做item_copymy_item. 我了解到这QQuickItem是不可复制的。所以,想要设置my_iteminto的所有属性item_copymy_item从而从头开始重建。我怎样才能做到这一点?我应该主要复制哪些属性?宽度,高度,x,y & 还有什么?

有没有一种方法可以将所有有效属性复制到这个新属性中而无需逐一复制?

4

1 回答 1

1

要复制所有属性,您必须使用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)
于 2017-09-08T14:30:12.163 回答