簡體   English   中英

如何將X和Y轉換后的值應用於C ++端的QQuickItem

[英]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");

是的,我可以通過以下方式獲得rectQuickItemxy

QQuickItem *rectQuickItemParent = qml_engine->rootObjects()[0]->findChild<QQuickItem*>("rectParentObject");
qreal item_x = rectQuickItem->x();
qreal item_y = rectQuickItem->y();

題:
但是,如何獲得rectQuickItem的x和y轉換?
我發現item_xitem_y不是實際應用於UI的x和y。 似乎是transform: Translaterect x和y添加了一些單位,當我查詢rectQuickItem->x()時我沒有得到。

用簡單的話來說 ,我需要在transform: Translate對x和y分別應用-20-30 transform: Translate rect_parent塊,最終將其應用於rect

目的:
我正在更改 rectQuickItem 的父級 ,以將其顯示在另一個窗口中,該窗口分別具有與原始父級相同的x和y位置。 由於transform: Translate ,我需要添加到rectQuickItem屬性的xy的單位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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM