|
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, parent=None): |
|
super(Model, self).__init__(parent) |
|
self._items = items |
|
|
|
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 { |
|
QtCore.Qt.UserRole + 0: "name", |
|
QtCore.Qt.UserRole + 1: "x", |
|
QtCore.Qt.UserRole + 2: "y", |
|
} |
|
|
|
|
|
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 |
|
canvas_width = 600 |
|
canvas_height = 500 |
|
node_width = 100 |
|
node_height = 50 |
|
scale = 10 |
|
|
|
nodes = list() |
|
for i in xrange(amount): |
|
x = random.randint(0, canvas_width - node_width) |
|
y = random.randint(0, canvas_height - node_height) |
|
|
|
nodes.append({ |
|
"name": "Node %s" % i, |
|
"x": x * scale, |
|
"y": y * scale |
|
}) |
|
|
|
model = Model(nodes) |
|
|
|
context = engine.rootContext() |
|
context.setContextProperty("sgModel", model) |
|
|
|
engine.load(QtCore.QUrl.fromLocalFile("main.qml")) |