File indexing completed on 2024-04-28 15:27:44

0001 /*
0002  *  SPDX-FileCopyrightText: 2017 Marco Martin <mart@kde.org>
0003  *
0004  *  SPDX-License-Identifier: LGPL-2.0-or-later
0005  */
0006 
0007 #include "scenepositionattached.h"
0008 #include <QDebug>
0009 #include <QQuickItem>
0010 
0011 ScenePositionAttached::ScenePositionAttached(QObject *parent)
0012     : QObject(parent)
0013 {
0014     m_item = qobject_cast<QQuickItem *>(parent);
0015     connectAncestors(m_item);
0016 }
0017 
0018 ScenePositionAttached::~ScenePositionAttached()
0019 {
0020 }
0021 
0022 int ScenePositionAttached::x() const
0023 {
0024     qreal x = 0;
0025     QQuickItem *item = m_item;
0026 
0027     while (item) {
0028         x += item->x();
0029         item = item->parentItem();
0030     }
0031 
0032     return x;
0033 }
0034 
0035 int ScenePositionAttached::y() const
0036 {
0037     qreal y = 0;
0038     QQuickItem *item = m_item;
0039 
0040     while (item) {
0041         y += item->y();
0042         item = item->parentItem();
0043     }
0044 
0045     return y;
0046 }
0047 
0048 void ScenePositionAttached::connectAncestors(QQuickItem *item)
0049 {
0050     if (!item) {
0051         return;
0052     }
0053 
0054     QQuickItem *ancestor = item;
0055     while (ancestor) {
0056         m_ancestors << ancestor;
0057 
0058         connect(ancestor, &QQuickItem::xChanged, this, &ScenePositionAttached::xChanged);
0059         connect(ancestor, &QQuickItem::yChanged, this, &ScenePositionAttached::yChanged);
0060         connect(ancestor, &QQuickItem::parentChanged, this, [this, ancestor]() {
0061             do {
0062                 disconnect(ancestor, nullptr, this, nullptr);
0063                 m_ancestors.pop_back();
0064             } while (!m_ancestors.isEmpty() && m_ancestors.last() != ancestor);
0065 
0066             connectAncestors(ancestor);
0067             Q_EMIT xChanged();
0068             Q_EMIT yChanged();
0069         });
0070 
0071         ancestor = ancestor->parentItem();
0072     }
0073 }
0074 
0075 ScenePositionAttached *ScenePositionAttached::qmlAttachedProperties(QObject *object)
0076 {
0077     return new ScenePositionAttached(object);
0078 }
0079 
0080 #include "moc_scenepositionattached.cpp"