|
import sys |
|
import random |
|
import contextlib |
|
from PyQt5 import QtQml, QtGui, QtCore |
|
|
|
|
|
@contextlib.contextmanager |
|
def application(): |
|
app = QtGui.QGuiApplication(sys.argv) |
|
yield |
|
app.exec_() |
|
|
|
|
|
class Model(QtCore.QAbstractListModel): |
|
def __init__(self, items, roles, parent=None): |
|
super(Model, self).__init__(parent) |
|
self._items = items |
|
self._roles = roles |
|
|
|
def rowCount(self, parent=None): |
|
return len(self._items) |
|
|
|
def data(self, index, role=QtCore.QModelIndex()): |
|
name = self.roleNames()[role] |
|
|
|
try: |
|
return self._items[index.row()][name] |
|
except KeyError: |
|
pass |
|
|
|
def roleNames(self): |
|
return self._roles |
|
|
|
|
|
if __name__ == '__main__': |
|
import argparse |
|
parser = argparse.ArgumentParser() |
|
parser.add_argument("--amount", type=int, default=100) |
|
|
|
amount = parser.parse_args().amount |
|
print("Creating %i nodes" % amount) |
|
|
|
with application(): |
|
engine = QtQml.QQmlApplicationEngine() |
|
|
|
# Generate lots of nodes |
|
scale = 1 |
|
|
|
nodes = list() |
|
x = 0 |
|
y = 0 |
|
for i in xrange(amount): |
|
x += random.randint(100, 150) |
|
y += random.randint(-100, 100) |
|
|
|
nodes.append({ |
|
"name": "Node %s" % i, |
|
"x": x * scale + 500, # Offset nodes towards center |
|
"y": y * scale + 1000 |
|
}) |
|
|
|
connections = list() |
|
for index, node in enumerate(nodes): |
|
if index == 0: |
|
continue |
|
|
|
# Next node connected to the previous node |
|
previous = nodes[index - 1] |
|
|
|
# Pythagoras a**2 + b**2 = c**2 |
|
connections.append({ |
|
"x1": node["x"] + 0, # Out position |
|
"y1": node["y"] + 25, |
|
"x2": previous["x"] + 100, # In position |
|
"y2": previous["y"] + 25, |
|
}) |
|
|
|
print("Nodes: %s" % nodes) |
|
print("Connections: %s" % connections) |
|
|
|
sg_model = Model(nodes, roles={ |
|
QtCore.Qt.UserRole + 0: "name", |
|
QtCore.Qt.UserRole + 1: "x", |
|
QtCore.Qt.UserRole + 2: "y", |
|
}) |
|
|
|
con_model = Model(connections, roles={ |
|
QtCore.Qt.UserRole + 1: "x1", |
|
QtCore.Qt.UserRole + 2: "y1", |
|
QtCore.Qt.UserRole + 3: "x2", |
|
QtCore.Qt.UserRole + 4: "y2", |
|
}) |
|
|
|
context = engine.rootContext() |
|
context.setContextProperty("sgModel", sg_model) |
|
context.setContextProperty("conModel", con_model) |
|
|
|
engine.load(QtCore.QUrl.fromLocalFile("main.qml")) |
Hi mottosso,
thank you so much for providing your code snippets!
The "Minimal QML SceneGraph 2" example is exactly what I'm looking for.
What license agreement does your code have?
Thanks in advance!
Many greetings from Germany!
Daniel