Kirigami2

scenepositionattached.cpp
1 /*
2  * SPDX-FileCopyrightText: 2017 Marco Martin <[email protected]>
3  *
4  * SPDX-License-Identifier: LGPL-2.0-or-later
5  */
6 
7 #include "scenepositionattached.h"
8 #include <QDebug>
9 #include <QQuickItem>
10 
11 ScenePositionAttached::ScenePositionAttached(QObject *parent)
12  : QObject(parent)
13 {
14  m_item = qobject_cast<QQuickItem *>(parent);
15  connectAncestors(m_item);
16 }
17 
18 ScenePositionAttached::~ScenePositionAttached()
19 {
20 }
21 
22 int ScenePositionAttached::x() const
23 {
24  qreal x = 0;
25  QQuickItem *item = m_item;
26 
27  while (item) {
28  x += item->x();
29  item = item->parentItem();
30  }
31 
32  return x;
33 }
34 
35 int ScenePositionAttached::y() const
36 {
37  qreal y = 0;
38  QQuickItem *item = m_item;
39 
40  while (item) {
41  y += item->y();
42  item = item->parentItem();
43  }
44 
45  return y;
46 }
47 
48 void ScenePositionAttached::connectAncestors(QQuickItem *item)
49 {
50  if (!item) {
51  return;
52  }
53 
54  QQuickItem *ancestor = item;
55  while (ancestor) {
56  m_ancestors << ancestor;
57 
58  connect(ancestor, &QQuickItem::xChanged, this, &ScenePositionAttached::xChanged);
59  connect(ancestor, &QQuickItem::yChanged, this, &ScenePositionAttached::yChanged);
60  connect(ancestor, &QQuickItem::parentChanged, this, [this, ancestor]() {
61  do {
62  disconnect(ancestor, nullptr, this, nullptr);
63  m_ancestors.pop_back();
64  } while (!m_ancestors.isEmpty() && m_ancestors.last() != ancestor);
65 
66  connectAncestors(ancestor);
67  Q_EMIT xChanged();
68  Q_EMIT yChanged();
69  });
70 
71  ancestor = ancestor->parentItem();
72  }
73 }
74 
75 ScenePositionAttached *ScenePositionAttached::qmlAttachedProperties(QObject *object)
76 {
77  return new ScenePositionAttached(object);
78 }
79 
80 #include "moc_scenepositionattached.cpp"
int x
The global scene X position.
QQuickItem * parentItem() const const
This attached property contains the information about the scene position of the item: Its global x an...
int y
The global scene Y position.
This file is part of the KDE documentation.
Documentation copyright © 1996-2023 The KDE developers.
Generated on Sun Jan 29 2023 04:11:03 by doxygen 1.8.17 written by Dimitri van Heesch, © 1997-2006

KDE's Doxygen guidelines are available online.