KDStateMachineEditor API Documentation  1.2.50
treewalker.h
1 /*
2  This file is part of the KDAB State Machine Editor Library.
3 
4  SPDX-FileCopyrightText: 2014-2021 Klarälvdalens Datakonsult AB, a KDAB Group company <info@kdab.com>
5  Author: Kevin Funk <kevin.funk@kdab.com>
6 
7  SPDX-License-Identifier: LGPL-2.1-only OR LicenseRef-KDAB-KDStateMachineEditor
8 
9  Licensees holding valid commercial KDAB State Machine Editor Library
10  licenses may use this file in accordance with the KDAB State Machine Editor
11  Library License Agreement provided with the Software.
12 
13  Contact info@kdab.com if any conditions of this licensing are not clear to you.
14 */
15 
16 #ifndef KDSME_UTIL_TREEWALKER_H
17 #define KDSME_UTIL_TREEWALKER_H
18 
19 #include "kdsme_core_export.h"
20 
21 #include <QObject>
22 
23 #include <functional>
24 
25 namespace KDSME {
26 
27 template<typename T>
29 {
30  static QList<T> children(T item) { Q_UNUSED(item); return QList<T>(); }
31 };
32 
38 template<typename T>
40 {
41 public:
42  enum VisitResult {
45  StopWalk
46  };
47 
48  enum TraversalType {
49  PreOrderTraversal,
50  PostOrderTraversal,
51  };
52 
53  typedef std::function<VisitResult(T)> VisitFunction;
54 
55  explicit TreeWalker(TraversalType type = PreOrderTraversal)
56  : m_traversalType(type) {}
57 
65  bool walkItems(T item, const VisitFunction& visit)
66  {
67  if (!item)
68  return false;
69 
70  bool continueWalk = true;
71  if (m_traversalType == PreOrderTraversal) {
72  continueWalk = (visit(item) == TreeWalker::RecursiveWalk);
73  }
74  Q_ASSERT(item);
75  foreach (T child, TreeWalkerTrait<T>::children(item)) {
76  if (!walkItems(child, visit))
77  return false;
78  }
79  if (m_traversalType == PostOrderTraversal) {
80  continueWalk = (visit(item) == TreeWalker::RecursiveWalk);
81  }
82  return continueWalk;
83  }
84 
90  bool walkChildren(T item, const VisitFunction& visit)
91  {
92  if (!item)
93  return false;
94 
95  foreach (T child, TreeWalkerTrait<T>::children(item)) {
96  if (!walkItems(child, visit))
97  return false;
98  }
99  return true;
100  }
101 
102 private:
103  TraversalType m_traversalType;
104 };
105 
106 }
107 
108 #endif // TREEWALKER_H
bool walkItems(T item, const VisitFunction &visit)
Definition: treewalker.h:65
bool walkChildren(T item, const VisitFunction &visit)
Definition: treewalker.h:90
Definition: treewalker.h:28
Traverse the children of this item.
Definition: treewalker.h:44
VisitResult
Definition: treewalker.h:42
Definition: treewalker.h:39
Continues traversal with the next sibling of the item just visited, without visiting its children...
Definition: treewalker.h:43
Definition: mainwindow.h:21

Klarälvdalens Datakonsult AB (KDAB)
"The Qt, C++ and OpenGL Experts"
https://www.kdab.com/
KDStateMachineEditor
Create Qt State Machine metacode using a graphical user interface
https://github.com/KDAB/KDStateMachineEditor