![](/img/trans.png)
[英]How to create a new QQuickItem copy from scratch on C++ side with the same properties as an existing one
[英]How to get the X and Y translated values applied to a QQuickItem on to the C++ side
我有以下具有父项的QML Rectangle
。 需要注意的最重要的一点是,它应用了Translate QML元素 ,我正努力了解该元素到底对QML项及其子项的作用。
码:
Window {
id: main_window
width: 640
height: 480
visible: true
Item {
id: rect_parent
objectName: "rect_parent_object"
x: 0
y: 0
width: parent.width
height: parent.height
transform: Translate {x: -20; y: -30}
Rectangle {
id: rect
objectName: "rect_object"
x: parent.width/2
y: parent.height/2
width: parent.width/3
height: parent.height/3
color: "red"
}
}
}
rect_parent
具有属性transform: Translate
如您在以上代码中所见进行转换。 以下是应用于它的XY平移
transform: Translate {x: -20; y: -20}
在main.cpp
中我的代码的C ++部分中,我通过以下方式获取QQuickItem
。
QQuickItem *rectQuickItem = qml_engine->rootObjects()[0]->findChild<QQuickItem*>("rectObject");
QQuickItem *rectQuickItemParent = qml_engine->rootObjects()[0]->findChild<QQuickItem*>("rectParentObject");
是的,我可以通过以下方式获得rectQuickItem
的x
和y
。
QQuickItem *rectQuickItemParent = qml_engine->rootObjects()[0]->findChild<QQuickItem*>("rectParentObject");
qreal item_x = rectQuickItem->x();
qreal item_y = rectQuickItem->y();
题:
但是,如何获得rectQuickItem
的x和y转换?
我发现item_x
和item_y
不是实际应用于UI的x和y。 似乎是transform: Translate
向rect
x和y添加了一些单位,当我查询rectQuickItem->x()
时我没有得到。
用简单的话来说 ,我需要在transform: Translate
对x和y分别应用-20
和-30
transform: Translate
rect_parent
块,最终将其应用于rect
目的:
我正在更改 rectQuickItem
的父级 ,以将其显示在另一个窗口中,该窗口分别具有与原始父级相同的x和y位置。 由于transform: Translate
,我需要添加到rectQuickItem
属性的x
和y
的单位transform: Translate
设置transform: Translate
以便在与上一个父级相同的位置显示rect
。
附加问题:
QQuickItem :: MapToItem可以在这里以任何方式帮助我吗?
如果要获取某个项目相对于另一个项目的坐标,则过程为:
static QPointF positionToAnotherItem(QQuickItem *source, QQuickItem *destine){
QPointF p = source->mapToScene(QPointF(0, 0));
return destine->mapFromScene(p);
}
static QPointF positionToParent(QQuickItem *item){
return positionToAnotherItem(item, item->parentItem());
}
转换不会立即应用,因此通过应用上述过程,您将无法获得正确的位置,必须在xChanged和YChanged信号的帮助下应用它们。
QQuickItem *rectQuickItem = qml_engine.rootObjects()[0]->findChild<QQuickItem*>("rect_object");
//QQuickItem *rectQuickItemParent = qml_engine.rootObjects()[0]->findChild<QQuickItem*>("rect_parent_object");
QObject::connect(rectQuickItem, &QQuickItem::xChanged, [rectQuickItem]{
qDebug()<<positionToParent(rectQuickItem);
});
QObject::connect(rectQuickItem, &QQuickItem::yChanged, [rectQuickItem]{
qDebug()<<positionToParent(rectQuickItem);
});
在下面的链接中有一个完整的示例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.