![](/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.