From 40d84f1b1f7779f9cd8fbd224cc6adc9e38f26db Mon Sep 17 00:00:00 2001 From: Dmitry Pinaev Date: Tue, 1 Dec 2026 11:13:06 +0100 Subject: [PATCH 1/6] Update the node after port changes, a load and a widget resize DataFlowGraphModel now emits nodeUpdated in three more cases, so that the scene recomputes the node size: - after a delegate inserts or deletes ports, once the shifted connections are restored; - after loadNode() restored the label and the delegate state, because nodeCreated comes before them; - when a delegate emits embeddedWidgetSizeUpdated, like requestNodeUpdate. The delegate signals are connected in one helper for addNode() and loadNode(). The header and the guide now say that a custom model must emit nodeUpdated after portsInserted() and portsDeleted(). --- docs/guide/advanced.rst | 9 + .../QtNodes/internal/AbstractGraphModel.hpp | 9 +- .../QtNodes/internal/DataFlowGraphModel.hpp | 3 + .../QtNodes/internal/NodeDelegateModel.hpp | 5 + src/DataFlowGraphModel.cpp | 113 +++++-------- test/CMakeLists.txt | 1 + test/src/TestNodeSizeUpdates.cpp | 154 ++++++++++++++++++ 7 files changed, 223 insertions(+), 71 deletions(-) create mode 100644 test/src/TestNodeSizeUpdates.cpp diff --git a/docs/guide/advanced.rst b/docs/guide/advanced.rst index 82ba18822..aeb5d326c 100644 --- a/docs/guide/advanced.rst +++ b/docs/guide/advanced.rst @@ -39,6 +39,9 @@ inputs like "Add N Numbers" or "Merge Arrays". // 3. Complete: library restores shifted connections portsInserted(); + + // 4. The port count changed: let the scene recompute the node size + emit nodeUpdated(nodeId); } void MyModel::removePortFromNode(NodeId nodeId, PortIndex portIndex) @@ -51,6 +54,9 @@ inputs like "Add N Numbers" or "Merge Arrays". // 3. Complete portsDeleted(); + + // 4. The port count changed: let the scene recompute the node size + emit nodeUpdated(nodeId); } **In NodeDelegateModel:** @@ -66,6 +72,9 @@ inputs like "Add N Numbers" or "Merge Arrays". emit portsInserted(); } +``DataFlowGraphModel`` updates the node after ``portsInserted()`` and ``portsDeleted()``. +A delegate does not need to emit ``requestNodeUpdate()`` for the port change. + .. warning:: Always use the two-phase approach. Modifying ports without the diff --git a/include/QtNodes/internal/AbstractGraphModel.hpp b/include/QtNodes/internal/AbstractGraphModel.hpp index 9901cd089..b948e4925 100644 --- a/include/QtNodes/internal/AbstractGraphModel.hpp +++ b/include/QtNodes/internal/AbstractGraphModel.hpp @@ -215,8 +215,10 @@ class NODE_EDITOR_PUBLIC AbstractGraphModel : public QObject PortIndex const last); /** - * Signal emitted when model no longer has the old data associated with the - * given port indices and when the node must be repainted. + * Function re-creates the connections that were shifted during the port + * deletion. Call it when the model no longer has the old data of the + * deleted ports. It does not update the node: the model must emit + * `nodeUpdated` after this call, so that the scene recomputes the size. */ void portsDeleted(); @@ -236,7 +238,8 @@ class NODE_EDITOR_PUBLIC AbstractGraphModel : public QObject /** * Function re-creates the connections that were shifted during the port - * insertion. After that the node is updated. + * insertion. It does not update the node: the model must emit + * `nodeUpdated` after this call, so that the scene recomputes the size. */ void portsInserted(); diff --git a/include/QtNodes/internal/DataFlowGraphModel.hpp b/include/QtNodes/internal/DataFlowGraphModel.hpp index de54d1992..426ae8cd6 100644 --- a/include/QtNodes/internal/DataFlowGraphModel.hpp +++ b/include/QtNodes/internal/DataFlowGraphModel.hpp @@ -113,6 +113,9 @@ class NODE_EDITOR_PUBLIC DataFlowGraphModel void sendConnectionDeletion(ConnectionId const connectionId); + /// Connects the signals of a new or restored delegate to this model. + void connectDelegateModel(NodeId const nodeId, NodeDelegateModel *model); + private Q_SLOTS: /** * Fuction is called in three cases: diff --git a/include/QtNodes/internal/NodeDelegateModel.hpp b/include/QtNodes/internal/NodeDelegateModel.hpp index bb359a452..4aef2d86e 100644 --- a/include/QtNodes/internal/NodeDelegateModel.hpp +++ b/include/QtNodes/internal/NodeDelegateModel.hpp @@ -163,6 +163,11 @@ public Q_SLOTS: void computingStarted(); void computingFinished(); + /** + * Emit this signal after the embedded widget changed its size. + * `DataFlowGraphModel` emits `nodeUpdated` for the node, like for + * `requestNodeUpdate`, so that the scene recomputes the node size. + */ void embeddedWidgetSizeUpdated(); /// Request an update of the node's UI. diff --git a/src/DataFlowGraphModel.cpp b/src/DataFlowGraphModel.cpp index 2a8128302..fa8be2a7e 100644 --- a/src/DataFlowGraphModel.cpp +++ b/src/DataFlowGraphModel.cpp @@ -59,6 +59,46 @@ bool DataFlowGraphModel::connectionExists(ConnectionId const connectionId) const return (_connectivity.find(connectionId) != _connectivity.end()); } +void DataFlowGraphModel::connectDelegateModel(NodeId const nodeId, NodeDelegateModel *model) +{ + connect(model, &NodeDelegateModel::dataUpdated, [nodeId, this](PortIndex const portIndex) { + onOutPortDataUpdated(nodeId, portIndex); + }); + + connect(model, + &NodeDelegateModel::portsAboutToBeDeleted, + this, + [nodeId, this](PortType const portType, PortIndex const first, PortIndex const last) { + portsAboutToBeDeleted(nodeId, portType, first, last); + }); + + // The port count changed, so the node size changes too. + connect(model, &NodeDelegateModel::portsDeleted, this, [nodeId, this]() { + portsDeleted(); + Q_EMIT nodeUpdated(nodeId); + }); + + connect(model, + &NodeDelegateModel::portsAboutToBeInserted, + this, + [nodeId, this](PortType const portType, PortIndex const first, PortIndex const last) { + portsAboutToBeInserted(nodeId, portType, first, last); + }); + + connect(model, &NodeDelegateModel::portsInserted, this, [nodeId, this]() { + portsInserted(); + Q_EMIT nodeUpdated(nodeId); + }); + + connect(model, &NodeDelegateModel::requestNodeUpdate, this, [nodeId, this]() { + Q_EMIT nodeUpdated(nodeId); + }); + + connect(model, &NodeDelegateModel::embeddedWidgetSizeUpdated, this, [nodeId, this]() { + Q_EMIT nodeUpdated(nodeId); + }); +} + NodeId DataFlowGraphModel::addNode(QString const nodeType) { std::unique_ptr model = _registry->create(nodeType); @@ -66,39 +106,7 @@ NodeId DataFlowGraphModel::addNode(QString const nodeType) if (model) { NodeId newId = newNodeId(); - connect(model.get(), - &NodeDelegateModel::dataUpdated, - [newId, this](PortIndex const portIndex) { - onOutPortDataUpdated(newId, portIndex); - }); - - connect(model.get(), - &NodeDelegateModel::portsAboutToBeDeleted, - this, - [newId, this](PortType const portType, PortIndex const first, PortIndex const last) { - portsAboutToBeDeleted(newId, portType, first, last); - }); - - connect(model.get(), - &NodeDelegateModel::portsDeleted, - this, - &DataFlowGraphModel::portsDeleted); - - connect(model.get(), - &NodeDelegateModel::portsAboutToBeInserted, - this, - [newId, this](PortType const portType, PortIndex const first, PortIndex const last) { - portsAboutToBeInserted(newId, portType, first, last); - }); - - connect(model.get(), - &NodeDelegateModel::portsInserted, - this, - &DataFlowGraphModel::portsInserted); - - connect(model.get(), &NodeDelegateModel::requestNodeUpdate, this, [newId, this]() { - Q_EMIT nodeUpdated(newId); - }); + connectDelegateModel(newId, model.get()); _models[newId] = std::move(model); @@ -613,41 +621,7 @@ void DataFlowGraphModel::loadNode(QJsonObject const &nodeJson) std::unique_ptr model = _registry->create(delegateModelName); if (model) { - connect(model.get(), - &NodeDelegateModel::dataUpdated, - [restoredNodeId, this](PortIndex const portIndex) { - onOutPortDataUpdated(restoredNodeId, portIndex); - }); - - connect(model.get(), - &NodeDelegateModel::portsAboutToBeDeleted, - this, - [restoredNodeId, - this](PortType const portType, PortIndex const first, PortIndex const last) { - portsAboutToBeDeleted(restoredNodeId, portType, first, last); - }); - - connect(model.get(), - &NodeDelegateModel::portsDeleted, - this, - &DataFlowGraphModel::portsDeleted); - - connect(model.get(), - &NodeDelegateModel::portsAboutToBeInserted, - this, - [restoredNodeId, - this](PortType const portType, PortIndex const first, PortIndex const last) { - portsAboutToBeInserted(restoredNodeId, portType, first, last); - }); - - connect(model.get(), - &NodeDelegateModel::portsInserted, - this, - &DataFlowGraphModel::portsInserted); - - connect(model.get(), &NodeDelegateModel::requestNodeUpdate, this, [restoredNodeId, this]() { - Q_EMIT nodeUpdated(restoredNodeId); - }); + connectDelegateModel(restoredNodeId, model.get()); _models[restoredNodeId] = std::move(model); @@ -665,6 +639,9 @@ void DataFlowGraphModel::loadNode(QJsonObject const &nodeJson) : restoredModel->labelVisible(); restoredModel->load(internalDataJson); + + // nodeCreated came before the label and the delegate state. Update the node once more. + Q_EMIT nodeUpdated(restoredNodeId); } else { throw std::logic_error(std::string("No registered model with name ") + delegateModelName.toLocal8Bit().data()); diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index a84d440b8..3bc7f8909 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -34,6 +34,7 @@ add_executable(test_nodes src/TestWidgetPosition.cpp src/TestOrientationWidgets.cpp src/TestViewDragMode.cpp + src/TestNodeSizeUpdates.cpp include/ApplicationSetup.hpp include/TestGraphModel.hpp include/UITestHelper.hpp diff --git a/test/src/TestNodeSizeUpdates.cpp b/test/src/TestNodeSizeUpdates.cpp new file mode 100644 index 000000000..5634a7758 --- /dev/null +++ b/test/src/TestNodeSizeUpdates.cpp @@ -0,0 +1,154 @@ +#include "ApplicationSetup.hpp" +#include "TestDataFlowNodes.hpp" +#include "TestDelegateModels.hpp" + +#include + +#include +#include +#include + +#include + +using QtNodes::BasicGraphicsScene; +using QtNodes::DataFlowGraphModel; +using QtNodes::NodeDelegateModelRegistry; +using QtNodes::NodeId; +using QtNodes::NodeRole; +using QtNodes::PortType; + +namespace { + +/// A delegate that adds and removes In ports at run time. +class DynamicInPorts : public StubDelegateModel +{ +public: + DynamicInPorts() + : StubDelegateModel("DynamicInPorts", "Dynamic") + {} + + unsigned int nPorts(PortType portType) const override + { + return portType == PortType::In ? _nIn : 1; + } + + void addInPort() + { + Q_EMIT portsAboutToBeInserted(PortType::In, _nIn, _nIn); + ++_nIn; + Q_EMIT portsInserted(); + } + + void removeInPort() + { + Q_EMIT portsAboutToBeDeleted(PortType::In, _nIn - 1, _nIn - 1); + --_nIn; + Q_EMIT portsDeleted(); + } + +private: + unsigned int _nIn = 1; +}; + +/// A source node that reports the size change of its widget. +class SizeReportingSource : public TestSourceNode +{ +public: + static QString Name() { return "SizeReportingSource"; } + QString name() const override { return Name(); } + + void growWidget() + { + embeddedWidget()->resize(embeddedWidget()->width() + 80, embeddedWidget()->height() + 60); + Q_EMIT embeddedWidgetSizeUpdated(); + } +}; + +std::shared_ptr makeRegistry() +{ + auto registry = std::make_shared(); + registry->registerModel("Test"); + registry->registerModel("Test"); + registry->registerModel([] { return std::make_unique(); }, "Test"); + return registry; +} + +QSize sizeOf(DataFlowGraphModel &model, NodeId id) +{ + return model.nodeData(id, NodeRole::Size).value(); +} + +} // namespace + +TEST_CASE("A node recomputes its size when its delegate inserts or deletes ports", + "[graphics][dynamic-ports]") +{ + auto app = applicationSetup(); + DataFlowGraphModel model(makeRegistry()); + BasicGraphicsScene scene(model); + + NodeId const id = model.addNode("DynamicInPorts"); + auto *delegate = model.delegateModel(id); + QSize const oneInPort = sizeOf(model, id); + + delegate->addInPort(); + QSize const twoInPorts = sizeOf(model, id); + CHECK(twoInPorts.height() > oneInPort.height()); + + // The size after the insert is the size that a full update computes. + scene.onNodeUpdated(id); + CHECK(sizeOf(model, id) == twoInPorts); + + delegate->removeInPort(); + CHECK(sizeOf(model, id) == oneInPort); +} + +TEST_CASE("A node loaded with a visible label has the size of a fully updated node", + "[graphics][serialization]") +{ + auto app = applicationSetup(); + auto registry = makeRegistry(); + + DataFlowGraphModel source(registry); + NodeId const id = source.addNode("TestDisplayNode"); + source.setNodeData(id, NodeRole::LabelVisible, true); + source.setNodeData(id, NodeRole::Label, QString("A rather long label for this node")); + QJsonObject const json = source.save(); + + DataFlowGraphModel model(registry); + BasicGraphicsScene scene(model); + QSignalSpy updated(&model, &DataFlowGraphModel::nodeUpdated); + + model.load(json); + + // One update per loaded node, after the label and the delegate state are restored. + CHECK(updated.count() == 1); + + NodeId const loaded = *model.allNodeIds().begin(); + QSize const afterLoad = sizeOf(model, loaded); + scene.onNodeUpdated(loaded); + CHECK(afterLoad == sizeOf(model, loaded)); +} + +TEST_CASE("embeddedWidgetSizeUpdated makes the node follow its widget, also after a load", + "[graphics][widget]") +{ + auto app = applicationSetup(); + DataFlowGraphModel model(makeRegistry()); + BasicGraphicsScene scene(model); + + NodeId const created = model.addNode("SizeReportingSource"); + + QJsonObject json = model.saveNode(created); + json["id"] = static_cast(created + 100); + model.loadNode(json); + NodeId const loaded = created + 100; + + for (NodeId const id : {created, loaded}) { + QSize const before = sizeOf(model, id); + model.delegateModel(id)->growWidget(); + QSize const after = sizeOf(model, id); + CHECK(after.width() == before.width() + 80); + CHECK(after.height() > before.height()); + } +} From ec729f05f1ea4723b2e660b985d4600b218c0ceb Mon Sep 17 00:00:00 2001 From: Dmitry Pinaev Date: Tue, 1 Dec 2026 11:46:07 +0100 Subject: [PATCH 2/6] Clear the undo stack when the graph is replaced and keep one undo action clearScene() deletes all nodes without an undo step, and onModelReset() rebuilds the scene from a new graph. The old commands then refer to nodes that no longer exist, and an undo could restore stale ids. Both now clear the undo stack. DataFlowGraphicsScene::load() calls clearScene(), so a load clears it too. GraphicsView::setScene() added a new Undo and Redo action on each call. It now deletes the actions of the previous scene. setScene(nullptr) also deletes the cut action, like the other actions. The undo guide listed a DuplicateCommand that does not exist. It now lists the real commands and says when the stack is cleared. --- docs/guide/undo-redo.rst | 18 +++- .../QtNodes/internal/BasicGraphicsScene.hpp | 1 + src/BasicGraphicsScene.cpp | 5 ++ src/GraphicsView.cpp | 17 ++++ test/CMakeLists.txt | 1 + test/src/TestSceneSetup.cpp | 83 +++++++++++++++++++ 6 files changed, 121 insertions(+), 4 deletions(-) create mode 100644 test/src/TestSceneSetup.cpp diff --git a/docs/guide/undo-redo.rst b/docs/guide/undo-redo.rst index 5e2ea36a1..0068a1899 100644 --- a/docs/guide/undo-redo.rst +++ b/docs/guide/undo-redo.rst @@ -14,7 +14,7 @@ automatically push commands to this stack: - Creating connections - Deleting connections - Moving nodes -- Duplicating nodes +- Pasting and duplicating nodes Accessing the Undo Stack ------------------------ @@ -47,10 +47,14 @@ QtNodes provides these ``QUndoCommand`` implementations in ``UndoCommands.cpp``: * - Command - Description + * - ``CreateCommand`` + - Creates a node * - ``DeleteCommand`` - Removes nodes and their connections - * - ``DuplicateCommand`` - - Duplicates selected nodes + * - ``CopyCommand`` + - Copies the selection to the clipboard. It does not stay on the stack + * - ``PasteCommand`` + - Inserts the nodes and connections from the clipboard * - ``DisconnectCommand`` - Removes a connection * - ``ConnectCommand`` @@ -58,6 +62,8 @@ QtNodes provides these ``QUndoCommand`` implementations in ``UndoCommands.cpp``: * - ``MoveNodeCommand`` - Moves a node to a new position +Duplicate has no command of its own. It pushes a ``CopyCommand`` and a ``PasteCommand``. + Serialization Requirement ------------------------- @@ -168,6 +174,10 @@ Use macros to group multiple commands: Clearing History ---------------- +``BasicGraphicsScene::clearScene()`` deletes the nodes without an undo step, so it clears the +stack. A ``modelReset`` and ``DataFlowGraphicsScene::load()`` clear it too. The commands on +the stack refer to nodes by id, and these nodes are gone. + .. code-block:: cpp // Clear all undo history @@ -189,7 +199,7 @@ Default shortcuts (handled by ``GraphicsView``): - ``Ctrl+Z`` -- Undo - ``Ctrl+Shift+Z`` or ``Ctrl+Y`` -- Redo - ``Delete`` -- Delete selection (creates ``DeleteCommand``) -- ``Ctrl+D`` -- Duplicate (creates ``DuplicateCommand``) +- ``Ctrl+D`` -- Duplicate (creates ``CopyCommand`` and ``PasteCommand``) .. seealso:: diff --git a/include/QtNodes/internal/BasicGraphicsScene.hpp b/include/QtNodes/internal/BasicGraphicsScene.hpp index 1e2bc2a4b..7af8ab134 100644 --- a/include/QtNodes/internal/BasicGraphicsScene.hpp +++ b/include/QtNodes/internal/BasicGraphicsScene.hpp @@ -103,6 +103,7 @@ class NODE_EDITOR_PUBLIC BasicGraphicsScene : public QGraphicsScene void resetDraftConnection(); /// Deletes all the nodes. Connections are removed automatically. + /// The deletion is not an undo step, so the function also clears the undo stack. void clearScene(); /** diff --git a/src/BasicGraphicsScene.cpp b/src/BasicGraphicsScene.cpp index 6dee57108..6c33e17d1 100644 --- a/src/BasicGraphicsScene.cpp +++ b/src/BasicGraphicsScene.cpp @@ -239,6 +239,9 @@ void BasicGraphicsScene::clearScene() for (auto nodeId : allNodeIds) { graphModel().deleteNode(nodeId); } + + // The deletion is not an undo step. + _undoStack->clear(); } std::vector> BasicGraphicsScene::connectionsWithinGroup(GroupId groupID) @@ -439,6 +442,8 @@ void BasicGraphicsScene::onModelReset() clear(); + _undoStack->clear(); + traverseGraphAndPopulateGraphicsObjects(); } diff --git a/src/GraphicsView.cpp b/src/GraphicsView.cpp index 51adad2dc..540a78627 100644 --- a/src/GraphicsView.cpp +++ b/src/GraphicsView.cpp @@ -83,18 +83,33 @@ QAction *GraphicsView::deleteSelectionAction() const return _deleteSelectionAction; } +namespace { + +// The undo and redo actions have no member pointer. Find the ones of the previous scene by name. +QString const undoActionName = QStringLiteral("QtNodesUndoAction"); +QString const redoActionName = QStringLiteral("QtNodesRedoAction"); + +} // namespace + void GraphicsView::setScene(BasicGraphicsScene *scene) { QGraphicsView::setScene(scene); + + for (QString const &name : {undoActionName, redoActionName}) { + qDeleteAll(findChildren(name, Qt::FindDirectChildrenOnly)); + } + if (!scene) { // Clear actions. delete _clearSelectionAction; delete _deleteSelectionAction; + delete _cutSelectionAction; delete _duplicateSelectionAction; delete _copySelectionAction; delete _pasteAction; _clearSelectionAction = nullptr; _deleteSelectionAction = nullptr; + _cutSelectionAction = nullptr; _duplicateSelectionAction = nullptr; _copySelectionAction = nullptr; _pasteAction = nullptr; @@ -181,10 +196,12 @@ void GraphicsView::setScene(BasicGraphicsScene *scene) } auto undoAction = scene->undoStack().createUndoAction(this, tr("&Undo")); + undoAction->setObjectName(undoActionName); undoAction->setShortcuts(QKeySequence::Undo); addAction(undoAction); auto redoAction = scene->undoStack().createRedoAction(this, tr("&Redo")); + redoAction->setObjectName(redoActionName); redoAction->setShortcuts(QKeySequence::Redo); addAction(redoAction); } diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 3bc7f8909..ee770075d 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -35,6 +35,7 @@ add_executable(test_nodes src/TestOrientationWidgets.cpp src/TestViewDragMode.cpp src/TestNodeSizeUpdates.cpp + src/TestSceneSetup.cpp include/ApplicationSetup.hpp include/TestGraphModel.hpp include/UITestHelper.hpp diff --git a/test/src/TestSceneSetup.cpp b/test/src/TestSceneSetup.cpp new file mode 100644 index 000000000..dc79f80df --- /dev/null +++ b/test/src/TestSceneSetup.cpp @@ -0,0 +1,83 @@ +#include "ApplicationSetup.hpp" +#include "TestGraphModel.hpp" + +#include +#include +#include + +#include + +#include +#include + +using QtNodes::BasicGraphicsScene; +using QtNodes::CreateCommand; +using QtNodes::GraphicsView; + +namespace { + +int countActionsWithShortcut(GraphicsView &view, QKeySequence::StandardKey key) +{ + int n = 0; + for (QAction *action : view.actions()) { + if (action->shortcuts().contains(QKeySequence(key))) + ++n; + } + return n; +} + +} // namespace + +TEST_CASE("Clearing the scene empties the undo stack", "[undo]") +{ + auto app = applicationSetup(); + TestGraphModel model; + BasicGraphicsScene scene(model); + + scene.undoStack().push(new CreateCommand(&scene, "TestNode", QPointF(0, 0))); + REQUIRE(scene.undoStack().count() == 1); + + scene.clearScene(); + + CHECK(scene.undoStack().count() == 0); +} + +TEST_CASE("A model reset empties the undo stack", "[undo]") +{ + auto app = applicationSetup(); + TestGraphModel model; + BasicGraphicsScene scene(model); + + scene.undoStack().push(new CreateCommand(&scene, "TestNode", QPointF(0, 0))); + REQUIRE(scene.undoStack().count() == 1); + + Q_EMIT model.modelReset(); + + CHECK(scene.undoStack().count() == 0); +} + +TEST_CASE("Setting the scene of a view again keeps one Undo and one Redo action", "[view]") +{ + auto app = applicationSetup(); + TestGraphModel model; + BasicGraphicsScene first(model); + BasicGraphicsScene second(model); + + GraphicsView view(&first); + view.setScene(&second); + view.setScene(&first); + + CHECK(countActionsWithShortcut(view, QKeySequence::Undo) == 1); + CHECK(countActionsWithShortcut(view, QKeySequence::Redo) == 1); + + // The actions belong to the stack of the current scene. + first.undoStack().push(new CreateCommand(&first, "TestNode", QPointF(0, 0))); + for (QAction *action : view.actions()) { + if (action->shortcuts().contains(QKeySequence(QKeySequence::Undo))) + CHECK(action->isEnabled()); + } + + view.setScene(nullptr); + CHECK(countActionsWithShortcut(view, QKeySequence::Undo) == 0); + CHECK(countActionsWithShortcut(view, QKeySequence::Redo) == 0); +} From e0159d433e57286ba81f9f529c3a76cc4d6c3504 Mon Sep 17 00:00:00 2001 From: Dmitry Pinaev Date: Tue, 1 Dec 2026 12:34:09 +0100 Subject: [PATCH 3/6] Keep connections on locked nodes and paste through the model A model-locked node turned off ItemSendsScenePositionChanges. The flag came with the first lock in 388666a, next to ItemIsMovable, but it does not stop a move: it only tells the item about one. A locked node moved from code or by undo then left its connections behind. The flag is now always on. The lock still clears ItemIsMovable and ItemIsSelectable, and the press handler still ignores a locked node. loadItems(..., usePastePos=true) moved a pasted node with moveBy(), so the model kept the old position. It now writes the position through the model. --- src/BasicGraphicsScene.cpp | 4 +- src/NodeGraphicsObject.cpp | 3 +- test/CMakeLists.txt | 1 + test/src/TestLockAndPaste.cpp | 101 ++++++++++++++++++++++++++++++++++ 4 files changed, 107 insertions(+), 2 deletions(-) create mode 100644 test/src/TestLockAndPaste.cpp diff --git a/src/BasicGraphicsScene.cpp b/src/BasicGraphicsScene.cpp index 6c33e17d1..51d1ce5f0 100644 --- a/src/BasicGraphicsScene.cpp +++ b/src/BasicGraphicsScene.cpp @@ -680,7 +680,9 @@ std::unordered_map BasicGraphicsScene::loadItems(const QByteArray offsetInitialized = true; } if (usePastePos) { - nodeRef.moveBy(offset.x(), offset.y()); + // Move through the model, so that the model and the item agree. + QPointF const pos = _graphModel.nodeData(newNodeId, NodeRole::Position); + _graphModel.setNodeData(newNodeId, NodeRole::Position, pos + offset); } nodeRef.moveConnections(); nodeRef.setSelected(true); diff --git a/src/NodeGraphicsObject.cpp b/src/NodeGraphicsObject.cpp index 03f5f6968..59d4b591d 100644 --- a/src/NodeGraphicsObject.cpp +++ b/src/NodeGraphicsObject.cpp @@ -33,6 +33,8 @@ NodeGraphicsObject::NodeGraphicsObject(BasicGraphicsScene &scene, NodeId nodeId) setFlag(QGraphicsItem::ItemDoesntPropagateOpacityToChildren, true); setFlag(QGraphicsItem::ItemIsFocusable, true); + // Connections follow the node through itemChange(), also when the node is locked. + setFlag(QGraphicsItem::ItemSendsScenePositionChanges, true); setLockedState(); @@ -130,7 +132,6 @@ void NodeGraphicsObject::setLockedState() // so that one lock does not undo the other. setFlag(QGraphicsItem::ItemIsMovable, !modelLocked); setFlag(QGraphicsItem::ItemIsSelectable, !modelLocked && !_locked); - setFlag(QGraphicsItem::ItemSendsScenePositionChanges, !modelLocked); setFlag(QGraphicsItem::ItemIsFocusable, !_locked); } diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index ee770075d..952ec36a3 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -36,6 +36,7 @@ add_executable(test_nodes src/TestViewDragMode.cpp src/TestNodeSizeUpdates.cpp src/TestSceneSetup.cpp + src/TestLockAndPaste.cpp include/ApplicationSetup.hpp include/TestGraphModel.hpp include/UITestHelper.hpp diff --git a/test/src/TestLockAndPaste.cpp b/test/src/TestLockAndPaste.cpp new file mode 100644 index 000000000..0f92780dd --- /dev/null +++ b/test/src/TestLockAndPaste.cpp @@ -0,0 +1,101 @@ +#include "ApplicationSetup.hpp" +#include "LockableModel.hpp" +#include "TestDataFlowNodes.hpp" +#include "TestGraphModel.hpp" + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include + +using QtNodes::BasicGraphicsScene; +using QtNodes::ConnectionId; +using QtNodes::DataFlowGraphModel; +using QtNodes::NodeDelegateModelRegistry; +using QtNodes::NodeFlag; +using QtNodes::NodeId; +using QtNodes::NodeRole; +using QtNodes::PortType; + +namespace { + +/// Counts the listeners of the signal for the lock state of a node. +class FlagsReceiversModel : public LockableModel +{ +public: + int flagsReceivers() const + { + QByteArray const signal + = "2" + QMetaMethod::fromSignal(&TestGraphModel::nodeFlagsUpdated).methodSignature(); + return receivers(signal.constData()); + } +}; + +QPointF connectionEnd(BasicGraphicsScene &scene, ConnectionId const &id, PortType portType) +{ + auto *cgo = scene.connectionGraphicsObject(id); + REQUIRE(cgo != nullptr); + return cgo->mapToScene(cgo->endPoint(portType)); +} + +QPointF portOnScene(BasicGraphicsScene &scene, NodeId id, PortType portType) +{ + auto *node = scene.nodeGraphicsObject(id); + REQUIRE(node != nullptr); + return scene.nodeGeometry().portScenePosition(id, portType, 0, node->sceneTransform()); +} + +} // namespace + +TEST_CASE("A model-locked node moved from code keeps its connections attached", "[node-lock]") +{ + auto app = applicationSetup(); + LockableModel model; + BasicGraphicsScene scene(model); + + NodeId const a = model.addNode("TestNode"); + NodeId const b = model.addNode("TestNode"); + model.setNodeData(b, NodeRole::Position, QPointF(300, 0)); + ConnectionId const c{a, 0, b, 0}; + model.addConnection(c); + + model.setLocked(a, true); + model.setNodeData(a, NodeRole::Position, QPointF(0, 200)); + + CHECK(connectionEnd(scene, c, PortType::Out) == portOnScene(scene, a, PortType::Out)); + + // The lock still keeps the node in place for the mouse. + auto *item = scene.nodeGraphicsObject(a); + CHECK_FALSE(item->flags().testFlag(QGraphicsItem::ItemIsMovable)); + CHECK_FALSE(item->flags().testFlag(QGraphicsItem::ItemIsSelectable)); +} + +TEST_CASE("Pasting at a position moves the node in the model, not only its item", "[copy-paste]") +{ + auto app = applicationSetup(); + auto registry = std::make_shared(); + registry->registerModel("Test"); + + DataFlowGraphModel source(registry); + NodeId const id = source.addNode("TestDisplayNode"); + source.setNodeData(id, NodeRole::Position, QPointF(10, 10)); + QByteArray const data = QJsonDocument(source.save()).toJson(); + + DataFlowGraphModel model(registry); + BasicGraphicsScene scene(model); + scene.loadItems(data, QPointF(500, 500), true); + + REQUIRE(model.allNodeIds().size() == 1); + NodeId const pasted = *model.allNodeIds().begin(); + + CHECK(model.nodeData(pasted, NodeRole::Position).toPointF() == QPointF(500, 500)); + CHECK(scene.nodeGraphicsObject(pasted)->pos() == QPointF(500, 500)); +} From 81105335d00ce824e01b17bee141d6da68a31d05 Mon Sep 17 00:00:00 2001 From: Dmitry Pinaev Date: Tue, 1 Dec 2026 13:20:03 +0100 Subject: [PATCH 4/6] Stop the endless repaint of a visible node group GroupGraphicsObject::paint() called prepareGeometryChange(), setRect() and positionLockedIcon(). Each call marked the item dirty and scheduled the next paint, so an idle view with one group repainted without end (3446 viewport paints in 300 ms in the new test). The group now computes its area in updateGeometry() and stores it in rect(). boundingRect() returns it, and paint() only draws. The area is recomputed when the group is created, when a node joins or leaves, when a possible child is set or cleared during a drag, and when a node of the group moves or changes its size (both end in moveConnections()). Part of paceholder/nodeeditor#537 (item 1). --- .../QtNodes/internal/GroupGraphicsObject.hpp | 6 + .../QtNodes/internal/NodeGraphicsObject.hpp | 1 + src/BasicGraphicsScene.cpp | 3 + src/GroupGraphicsObject.cpp | 21 ++- src/NodeGraphicsObject.cpp | 9 ++ src/NodeGroup.cpp | 9 +- test/CMakeLists.txt | 1 + test/src/TestGroupRepaint.cpp | 133 ++++++++++++++++++ 8 files changed, 176 insertions(+), 7 deletions(-) create mode 100644 test/src/TestGroupRepaint.cpp diff --git a/include/QtNodes/internal/GroupGraphicsObject.hpp b/include/QtNodes/internal/GroupGraphicsObject.hpp index 474c3f4d1..116cc0986 100644 --- a/include/QtNodes/internal/GroupGraphicsObject.hpp +++ b/include/QtNodes/internal/GroupGraphicsObject.hpp @@ -83,6 +83,12 @@ class NODE_EDITOR_PUBLIC GroupGraphicsObject */ QRectF boundingRect() const override; + /** + * @brief Recomputes the group area from the areas of its nodes. It is called + * when a node of the group moves, changes its size, joins or leaves. + */ + void updateGeometry(); + enum { Type = UserType + 3 }; /** diff --git a/include/QtNodes/internal/NodeGraphicsObject.hpp b/include/QtNodes/internal/NodeGraphicsObject.hpp index e3226802e..2e8c88ff5 100644 --- a/include/QtNodes/internal/NodeGraphicsObject.hpp +++ b/include/QtNodes/internal/NodeGraphicsObject.hpp @@ -97,6 +97,7 @@ class NODE_EDITOR_PUBLIC NodeGraphicsObject : public QGraphicsObject private: void embedQWidget(); void setLockedState(); + void updateGroupGeometry() const; private: NodeId _nodeId; diff --git a/src/BasicGraphicsScene.cpp b/src/BasicGraphicsScene.cpp index 51d1ce5f0..c08931c70 100644 --- a/src/BasicGraphicsScene.cpp +++ b/src/BasicGraphicsScene.cpp @@ -420,6 +420,9 @@ void BasicGraphicsScene::onNodeUpdated(NodeId const nodeId) node->updateQWidgetEmbedPos(); node->update(); node->moveConnections(); + + if (auto group = node->nodeGroup().lock()) + group->groupGraphicsObject().updateGeometry(); } } diff --git a/src/GroupGraphicsObject.cpp b/src/GroupGraphicsObject.cpp index 1aac8e611..78499e105 100644 --- a/src/GroupGraphicsObject.cpp +++ b/src/GroupGraphicsObject.cpp @@ -58,6 +58,8 @@ GroupGraphicsObject::GroupGraphicsObject(BasicGraphicsScene &scene, NodeGroup &n setZValue(-_groupAreaZValue); setAcceptHoverEvents(true); + + updateGeometry(); } GroupGraphicsObject::~GroupGraphicsObject() @@ -76,6 +78,11 @@ NodeGroup const &GroupGraphicsObject::group() const } QRectF GroupGraphicsObject::boundingRect() const +{ + return rect(); +} + +void GroupGraphicsObject::updateGeometry() { QRectF ret{}; for (auto &node : _group.childNodes()) { @@ -84,7 +91,14 @@ QRectF GroupGraphicsObject::boundingRect() const if (_possibleChild) { ret |= _possibleChild->mapRectToScene(_possibleChild->boundingRect()); } - return mapRectFromScene(ret.marginsAdded(_margins)); + + QRectF const newRect = mapRectFromScene(ret.marginsAdded(_margins)); + if (newRect == rect()) + return; + + // setRect() calls prepareGeometryChange(). + setRect(newRect); + positionLockedIcon(); } void GroupGraphicsObject::setFillColor(const QColor &color) @@ -159,11 +173,13 @@ void GroupGraphicsObject::setHovered(bool hovered) void GroupGraphicsObject::setPossibleChild(QtNodes::NodeGraphicsObject *possibleChild) { _possibleChild = possibleChild; + updateGeometry(); } void GroupGraphicsObject::unsetPossibleChild() { _possibleChild = nullptr; + updateGeometry(); } std::vector> GroupGraphicsObject::connections() const @@ -230,9 +246,6 @@ void GroupGraphicsObject::paint(QPainter *painter, QWidget *widget) { Q_UNUSED(widget); - prepareGeometryChange(); - setRect(boundingRect()); - positionLockedIcon(); painter->setClipRect(option->exposedRect); painter->setBrush(_currentFillColor); diff --git a/src/NodeGraphicsObject.cpp b/src/NodeGraphicsObject.cpp index 59d4b591d..d0cf615f4 100644 --- a/src/NodeGraphicsObject.cpp +++ b/src/NodeGraphicsObject.cpp @@ -164,6 +164,13 @@ void NodeGraphicsObject::moveConnections() const } } +void NodeGraphicsObject::updateGroupGeometry() const +{ + // The box of the group contains this node, so it follows each change of the node area. + if (auto group = _nodeGroup.lock()) + group->groupGraphicsObject().updateGeometry(); +} + void NodeGraphicsObject::reactToConnection(ConnectionGraphicsObject const *cgo) { _nodeState.storeConnectionForReaction(cgo); @@ -192,6 +199,7 @@ QVariant NodeGraphicsObject::itemChange(GraphicsItemChange change, const QVarian { if (change == ItemScenePositionHasChanged && scene()) { moveConnections(); + updateGroupGeometry(); } return QGraphicsObject::itemChange(change, value); @@ -310,6 +318,7 @@ void NodeGraphicsObject::mouseMoveEvent(QGraphicsSceneMouseEvent *event) update(); moveConnections(); + updateGroupGeometry(); event->accept(); } diff --git a/src/NodeGroup.cpp b/src/NodeGroup.cpp index 8406b2c8a..bee153257 100644 --- a/src/NodeGroup.cpp +++ b/src/NodeGroup.cpp @@ -117,8 +117,10 @@ int NodeGroup::groupCount() void NodeGroup::addNode(NodeGraphicsObject *node) { _childNodes.push_back(node); - if (_groupGraphicsObject && _groupGraphicsObject->locked()) { - node->lock(true); + if (_groupGraphicsObject) { + if (_groupGraphicsObject->locked()) + node->lock(true); + _groupGraphicsObject->updateGeometry(); } } @@ -129,6 +131,7 @@ void NodeGroup::removeNode(NodeGraphicsObject *node) if (nodeIt != _childNodes.end()) { (*nodeIt)->unsetNodeGroup(); _childNodes.erase(nodeIt); - groupGraphicsObject().positionLockedIcon(); + if (_groupGraphicsObject) + _groupGraphicsObject->updateGeometry(); } } diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 952ec36a3..abde90945 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -37,6 +37,7 @@ add_executable(test_nodes src/TestNodeSizeUpdates.cpp src/TestSceneSetup.cpp src/TestLockAndPaste.cpp + src/TestGroupRepaint.cpp include/ApplicationSetup.hpp include/TestGraphModel.hpp include/UITestHelper.hpp diff --git a/test/src/TestGroupRepaint.cpp b/test/src/TestGroupRepaint.cpp new file mode 100644 index 000000000..39ac6cbbd --- /dev/null +++ b/test/src/TestGroupRepaint.cpp @@ -0,0 +1,133 @@ +#include "ApplicationSetup.hpp" +#include "TestGraphModel.hpp" +#include "UITestHelper.hpp" + +#include +#include +#include +#include +#include + +#include + +#include +#include + +using QtNodes::BasicGraphicsScene; +using QtNodes::ConnectionId; +using QtNodes::GraphicsView; +using QtNodes::NodeGraphicsObject; +using QtNodes::NodeId; +using QtNodes::NodeRole; + +namespace { + +/// Counts the paint events of a widget. +class PaintCounter : public QObject +{ +public: + int paints = 0; + +protected: + bool eventFilter(QObject *watched, QEvent *event) override + { + if (event->type() == QEvent::Paint) + ++paints; + return QObject::eventFilter(watched, event); + } +}; + +bool groupContains(QtNodes::GroupGraphicsObject &group, NodeGraphicsObject &node) +{ + return group.sceneBoundingRect().contains(node.sceneBoundingRect()); +} + +} // namespace + +TEST_CASE("An idle view with a node group does not repaint", "[node-group][paint]") +{ + auto app = applicationSetup(); + TestGraphModel model; + BasicGraphicsScene scene(model); + GraphicsView view(&scene); + view.resize(800, 600); + view.show(); + REQUIRE(QTest::qWaitForWindowExposed(&view)); + + NodeId const a = model.addNode("TestNode"); + NodeId const b = model.addNode("TestNode"); + model.setNodeData(b, NodeRole::Position, QPointF(250, 0)); + model.addConnection(ConnectionId{a, 0, b, 0}); + + std::vector nodes{scene.nodeGraphicsObject(a), + scene.nodeGraphicsObject(b)}; + REQUIRE_FALSE(scene.createGroup(nodes, "Group").expired()); + UITestHelper::waitForUI(100); + + PaintCounter counter; + view.viewport()->installEventFilter(&counter); + UITestHelper::waitForUI(300); + + CHECK(counter.paints == 0); +} + +TEST_CASE("The box of a group follows its nodes when they move, join or leave", "[node-group]") +{ + auto app = applicationSetup(); + TestGraphModel model; + BasicGraphicsScene scene(model); + + NodeId const a = model.addNode("TestNode"); + NodeId const b = model.addNode("TestNode"); + NodeId const c = model.addNode("TestNode"); + model.setNodeData(b, NodeRole::Position, QPointF(250, 0)); + model.setNodeData(c, NodeRole::Position, QPointF(0, 600)); + + auto *nodeA = scene.nodeGraphicsObject(a); + auto *nodeB = scene.nodeGraphicsObject(b); + auto *nodeC = scene.nodeGraphicsObject(c); + + std::vector nodes{nodeA, nodeB}; + auto group = scene.createGroup(nodes, "Group").lock(); + REQUIRE(group); + auto &box = group->groupGraphicsObject(); + + CHECK(groupContains(box, *nodeA)); + CHECK(groupContains(box, *nodeB)); + CHECK_FALSE(groupContains(box, *nodeC)); + + model.setNodeData(b, NodeRole::Position, QPointF(900, 400)); + CHECK(groupContains(box, *nodeB)); + + scene.addNodeToGroup(c, group->id()); + CHECK(groupContains(box, *nodeC)); + + scene.removeNodeFromGroup(c); + CHECK_FALSE(groupContains(box, *nodeC)); +} + +TEST_CASE("The box of a group follows a node that changes its size", "[node-group]") +{ + auto app = applicationSetup(); + TestGraphModel model; + BasicGraphicsScene scene(model); + + NodeId const a = model.addNode("TestNode"); + NodeId const b = model.addNode("TestNode"); + model.setNodeData(b, NodeRole::Position, QPointF(250, 0)); + + auto *nodeB = scene.nodeGraphicsObject(b); + std::vector nodes{scene.nodeGraphicsObject(a), nodeB}; + auto group = scene.createGroup(nodes, "Group").lock(); + REQUIRE(group); + auto &box = group->groupGraphicsObject(); + + qreal const widthBefore = nodeB->sceneBoundingRect().width(); + + // A longer caption makes the node wider. + model.setNodeData(b, NodeRole::Caption, QString(60, 'W')); + Q_EMIT model.nodeUpdated(b); + + REQUIRE(nodeB->sceneBoundingRect().width() > widthBefore); + CHECK(groupContains(box, *nodeB)); +} From c97b164bf99df6c2ed466bcf82a149de05be6c0c Mon Sep 17 00:00:00 2001 From: Dmitry Pinaev Date: Tue, 1 Dec 2026 14:36:37 +0100 Subject: [PATCH 5/6] Add the connection signals that nodes already have and document the delegate signals BasicGraphicsScene gets connectionSelected and connectionDoubleClicked. ConnectionGraphicsObject emits them like NodeGraphicsObject emits nodeSelected and nodeDoubleClicked. The new signals are appended at the end of the signal list. Nothing existing changes. The headers and the guide now say who listens to the delegate signals: embeddedWidgetSizeUpdated updates the node, while computingStarted and computingFinished are for the application only. The guide also says that a custom model must emit nodeUpdated after a port change. See paceholder/nodeeditor#551 --- docs/guide/data-flow.rst | 21 +++- docs/guide/graph-models.rst | 22 +++++ docs/guide/visualization.rst | 9 ++ .../QtNodes/internal/BasicGraphicsScene.hpp | 6 ++ .../internal/ConnectionGraphicsObject.hpp | 2 + .../QtNodes/internal/NodeDelegateModel.hpp | 11 ++- src/ConnectionGraphicsObject.cpp | 12 +++ test/CMakeLists.txt | 1 + test/src/TestNotifications.cpp | 96 +++++++++++++++++++ 9 files changed, 176 insertions(+), 4 deletions(-) create mode 100644 test/src/TestNotifications.cpp diff --git a/docs/guide/data-flow.rst b/docs/guide/data-flow.rst index b8a2c19af..73db10017 100644 --- a/docs/guide/data-flow.rst +++ b/docs/guide/data-flow.rst @@ -177,8 +177,25 @@ Implementing Data Flow **Signals to emit:** -- ``dataUpdated(portIndex)`` -- Output data changed, propagate downstream -- ``dataInvalidated(portIndex)`` -- Output is no longer valid +- ``dataUpdated(portIndex)`` -- Output data changed. ``DataFlowGraphModel`` calls + ``outData()`` and sends the value to all connected inputs. To clear the inputs + downstream, return ``nullptr`` from ``outData()`` and emit ``dataUpdated``. +- ``requestNodeUpdate()`` -- Something visible changed that has no signal of its own, + for example after ``setNodeStyle()``, ``setNodeProcessingStatus()``, + ``setValidationState()`` or ``setProgressValue()``. The model emits ``nodeUpdated`` + and the scene recomputes the size and repaints the node. +- ``embeddedWidgetSizeUpdated()`` -- The embedded widget changed its size. The model + emits ``nodeUpdated``, like for ``requestNodeUpdate()``. +- ``portsAboutToBeInserted()`` / ``portsInserted()`` and ``portsAboutToBeDeleted()`` / + ``portsDeleted()`` -- The port count changes. See :doc:`advanced`. The model fixes the + connections, emits its port signals and then ``nodeUpdated``. + +**Signals for the application:** + +``dataInvalidated(portIndex)``, ``computingStarted()`` and ``computingFinished()`` have no +listener in the library. Emitting them changes nothing in the model or on the scene. Your +application can connect to them, for example to show a busy state. ``dataInvalidated`` +does not clear the data downstream; emit ``dataUpdated`` with a ``nullptr`` output for that. Data Flow Diagram ----------------- diff --git a/docs/guide/graph-models.rst b/docs/guide/graph-models.rst index fed51af6c..a33622f44 100644 --- a/docs/guide/graph-models.rst +++ b/docs/guide/graph-models.rst @@ -279,6 +279,28 @@ Your model **must** emit these signals at the appropriate times: // After removing a connection emit connectionDeleted(connectionId); + // After nodeFlags() changed, for example a node was locked + emit nodeFlagsUpdated(nodeId); + +Do not emit ``nodeUpdated`` when ``NodeRole::Size`` is set. The scene sets ``Size`` +while it handles ``nodeUpdated``. + +Emit ``modelReset()`` only when you replace the whole graph. The scene deletes all +items, groups and embedded widgets, builds them again and clears the undo stack. + +When the port count of a node changes, call the connection fix-up methods around the +change and emit ``nodeUpdated`` at the end, so that the scene recomputes the node size: + +.. code-block:: cpp + + portsAboutToBeInserted(nodeId, PortType::In, first, last); // fixes connections + // ... change the port count ... + portsInserted(); // restores connections + emit nodeUpdated(nodeId); + +The deletion is the same with ``portsAboutToBeDeleted()`` and ``portsDeleted()``. +``DataFlowGraphModel`` does all of this when a delegate changes its ports. + .. warning:: Forgetting to emit signals will cause the view to become out of sync diff --git a/docs/guide/visualization.rst b/docs/guide/visualization.rst index 6e2265f02..e3defcbee 100644 --- a/docs/guide/visualization.rst +++ b/docs/guide/visualization.rst @@ -237,6 +237,15 @@ Connect to user interactions: // Show connection info }); + // Connection interactions + connect(&scene, &BasicGraphicsScene::connectionSelected, [](ConnectionId id) { + // Show the connection in a side panel + }); + + connect(&scene, &BasicGraphicsScene::connectionDoubleClicked, [](ConnectionId id) { + // Open an editor for the connection + }); + // Context menus connect(&scene, &BasicGraphicsScene::nodeContextMenu, [](NodeId id, QPointF scenePos) { diff --git a/include/QtNodes/internal/BasicGraphicsScene.hpp b/include/QtNodes/internal/BasicGraphicsScene.hpp index 7af8ab134..756d2fd85 100644 --- a/include/QtNodes/internal/BasicGraphicsScene.hpp +++ b/include/QtNodes/internal/BasicGraphicsScene.hpp @@ -281,6 +281,12 @@ class NODE_EDITOR_PUBLIC BasicGraphicsScene : public QGraphicsScene void zoomFitAllClicked(); void zoomFitSelectedClicked(); + /// A press on a connection left it selected. Like `nodeSelected` for nodes. + void connectionSelected(ConnectionId const connectionId); + + /// A double click on a connection. Like `nodeDoubleClicked` for nodes. + void connectionDoubleClicked(ConnectionId const connectionId); + private: /** * @brief Creates Node and Connection graphics objects. diff --git a/include/QtNodes/internal/ConnectionGraphicsObject.hpp b/include/QtNodes/internal/ConnectionGraphicsObject.hpp index 03c06a03d..d638483b0 100644 --- a/include/QtNodes/internal/ConnectionGraphicsObject.hpp +++ b/include/QtNodes/internal/ConnectionGraphicsObject.hpp @@ -73,6 +73,8 @@ class NODE_EDITOR_PUBLIC ConnectionGraphicsObject : public QGraphicsObject void hoverLeaveEvent(QGraphicsSceneHoverEvent *event) override; + void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) override; + private: void initializePosition(); diff --git a/include/QtNodes/internal/NodeDelegateModel.hpp b/include/QtNodes/internal/NodeDelegateModel.hpp index 4aef2d86e..5a1e389a2 100644 --- a/include/QtNodes/internal/NodeDelegateModel.hpp +++ b/include/QtNodes/internal/NodeDelegateModel.hpp @@ -154,12 +154,19 @@ public Q_SLOTS: virtual void outputConnectionDeleted(ConnectionId const &) {} Q_SIGNALS: - /// Triggers the updates in the nodes downstream. + /// Triggers the updates in the nodes downstream. `DataFlowGraphModel` calls + /// `outData(index)` and sends the result to all connected inputs. A `nullptr` + /// output clears the inputs downstream. void dataUpdated(PortIndex const index); - /// Triggers the propagation of the empty data downstream. + /** + * Tells the application that the output at `index` is no longer valid. + * The library does not listen to this signal: it does not propagate + * empty data downstream. Emit `dataUpdated` with a `nullptr` output for that. + */ void dataInvalidated(PortIndex const index); + /// For the application. The library does not listen to these signals. void computingStarted(); void computingFinished(); diff --git a/src/ConnectionGraphicsObject.cpp b/src/ConnectionGraphicsObject.cpp index 05ae46b34..b392a53cb 100644 --- a/src/ConnectionGraphicsObject.cpp +++ b/src/ConnectionGraphicsObject.cpp @@ -14,6 +14,7 @@ #include #include +#include #include #include #include @@ -204,6 +205,17 @@ void ConnectionGraphicsObject::paint(QPainter *painter, void ConnectionGraphicsObject::mousePressEvent(QGraphicsSceneMouseEvent *event) { QGraphicsItem::mousePressEvent(event); + + if (isSelected()) { + Q_EMIT nodeScene()->connectionSelected(connectionId()); + } +} + +void ConnectionGraphicsObject::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) +{ + QGraphicsItem::mouseDoubleClickEvent(event); + + Q_EMIT nodeScene()->connectionDoubleClicked(connectionId()); } void ConnectionGraphicsObject::mouseMoveEvent(QGraphicsSceneMouseEvent *event) diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index abde90945..36e9e1b93 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -38,6 +38,7 @@ add_executable(test_nodes src/TestSceneSetup.cpp src/TestLockAndPaste.cpp src/TestGroupRepaint.cpp + src/TestNotifications.cpp include/ApplicationSetup.hpp include/TestGraphModel.hpp include/UITestHelper.hpp diff --git a/test/src/TestNotifications.cpp b/test/src/TestNotifications.cpp new file mode 100644 index 000000000..9c62dff11 --- /dev/null +++ b/test/src/TestNotifications.cpp @@ -0,0 +1,96 @@ +#include "ApplicationSetup.hpp" +#include "TestGraphModel.hpp" +#include "UITestHelper.hpp" + +#include +#include +#include + +#include + +#include + +using QtNodes::BasicGraphicsScene; +using QtNodes::ConnectionId; +using QtNodes::GraphicsView; +using QtNodes::NodeId; +using QtNodes::NodeRole; +using QtNodes::PortType; + +Q_DECLARE_METATYPE(QtNodes::ConnectionId) + +namespace { + +struct SceneWithConnection +{ + SceneWithConnection() + : scene(model) + , view(&scene) + { + qRegisterMetaType("ConnectionId"); + + view.resize(1000, 600); + view.show(); + REQUIRE(QTest::qWaitForWindowExposed(&view)); + + NodeId const a = model.addNode("TestNode"); + NodeId const b = model.addNode("TestNode"); + model.setNodeData(b, NodeRole::Position, QPointF(600, 0)); + connection = ConnectionId{a, 0, b, 0}; + model.addConnection(connection); + UITestHelper::waitForUI(); + + auto *cgo = scene.connectionGraphicsObject(connection); + REQUIRE(cgo != nullptr); + QPointF const out = cgo->mapToScene(cgo->endPoint(PortType::Out)); + QPointF const in = cgo->mapToScene(cgo->endPoint(PortType::In)); + middle = (out + in) / 2.0; + REQUIRE(scene.itemAt(middle, view.transform()) == cgo); + } + + TestGraphModel model; + BasicGraphicsScene scene; + GraphicsView view; + ConnectionId connection; + QPointF middle; +}; + +} // namespace + +TEST_CASE("A click on a connection emits connectionSelected once", "[graphics][signals]") +{ + auto app = applicationSetup(); + SceneWithConnection f; + QSignalSpy spy(&f.scene, &BasicGraphicsScene::connectionSelected); + + UITestHelper::simulateMousePress(&f.view, f.middle); + UITestHelper::simulateMouseRelease(&f.view, f.middle); + + REQUIRE(spy.count() == 1); + CHECK(spy.at(0).at(0).value() == f.connection); + CHECK(f.scene.connectionGraphicsObject(f.connection)->isSelected()); +} + +TEST_CASE("A double click on a connection emits connectionDoubleClicked once", + "[graphics][signals]") +{ + auto app = applicationSetup(); + SceneWithConnection f; + QSignalSpy spy(&f.scene, &BasicGraphicsScene::connectionDoubleClicked); + + UITestHelper::simulateMousePress(&f.view, f.middle); + UITestHelper::simulateMouseRelease(&f.view, f.middle); + + QPoint const viewPos = f.view.mapFromScene(f.middle); + QMouseEvent doubleClick(QEvent::MouseButtonDblClick, + viewPos, + f.view.viewport()->mapToGlobal(viewPos), + Qt::LeftButton, + Qt::LeftButton, + Qt::NoModifier); + QApplication::sendEvent(f.view.viewport(), &doubleClick); + UITestHelper::simulateMouseRelease(&f.view, f.middle); + + REQUIRE(spy.count() == 1); + CHECK(spy.at(0).at(0).value() == f.connection); +} From 6a016c00263eba75b6fbf7c44dae6fe3d31bd352 Mon Sep 17 00:00:00 2001 From: Dmitry Pinaev Date: Wed, 2 Dec 2026 00:33:01 +0100 Subject: [PATCH 6/6] Send empty data downstream when a delegate emits dataInvalidated The 2.x library cleared the connected inputs on dataInvalidated. The 3.x rewrite dropped the listener, so the calculator and node_validation examples kept showing the last valid value. DataFlowGraphModel now sends empty data to the inputs that are connected to the port. --- docs/guide/data-flow.rst | 10 ++- .../QtNodes/internal/DataFlowGraphModel.hpp | 2 + .../QtNodes/internal/NodeDelegateModel.hpp | 6 +- src/DataFlowGraphModel.cpp | 16 ++++ test/CMakeLists.txt | 1 + test/src/TestDataInvalidated.cpp | 84 +++++++++++++++++++ 6 files changed, 112 insertions(+), 7 deletions(-) create mode 100644 test/src/TestDataInvalidated.cpp diff --git a/docs/guide/data-flow.rst b/docs/guide/data-flow.rst index 73db10017..2f161af4b 100644 --- a/docs/guide/data-flow.rst +++ b/docs/guide/data-flow.rst @@ -180,6 +180,9 @@ Implementing Data Flow - ``dataUpdated(portIndex)`` -- Output data changed. ``DataFlowGraphModel`` calls ``outData()`` and sends the value to all connected inputs. To clear the inputs downstream, return ``nullptr`` from ``outData()`` and emit ``dataUpdated``. +- ``dataInvalidated(portIndex)`` -- Output is no longer valid. ``DataFlowGraphModel`` sends + empty data (``nullptr``) to all connected inputs. ``dataUpdated`` with a ``nullptr`` + output has the same effect. - ``requestNodeUpdate()`` -- Something visible changed that has no signal of its own, for example after ``setNodeStyle()``, ``setNodeProcessingStatus()``, ``setValidationState()`` or ``setProgressValue()``. The model emits ``nodeUpdated`` @@ -192,10 +195,9 @@ Implementing Data Flow **Signals for the application:** -``dataInvalidated(portIndex)``, ``computingStarted()`` and ``computingFinished()`` have no -listener in the library. Emitting them changes nothing in the model or on the scene. Your -application can connect to them, for example to show a busy state. ``dataInvalidated`` -does not clear the data downstream; emit ``dataUpdated`` with a ``nullptr`` output for that. +``computingStarted()`` and ``computingFinished()`` have no listener in the library. Emitting +them changes nothing in the model or on the scene. Your application can connect to them, for +example to show a busy state, as the ``calculator`` example does. Data Flow Diagram ----------------- diff --git a/include/QtNodes/internal/DataFlowGraphModel.hpp b/include/QtNodes/internal/DataFlowGraphModel.hpp index 426ae8cd6..f378412d9 100644 --- a/include/QtNodes/internal/DataFlowGraphModel.hpp +++ b/include/QtNodes/internal/DataFlowGraphModel.hpp @@ -129,6 +129,8 @@ private Q_SLOTS: */ void onOutPortDataUpdated(NodeId const nodeId, PortIndex const portIndex); + void onOutPortDataInvalidated(NodeId const nodeId, PortIndex const portIndex); + /// Function is called after detaching a connection. void propagateEmptyDataTo(NodeId const nodeId, PortIndex const portIndex); diff --git a/include/QtNodes/internal/NodeDelegateModel.hpp b/include/QtNodes/internal/NodeDelegateModel.hpp index 5a1e389a2..7062fc5c3 100644 --- a/include/QtNodes/internal/NodeDelegateModel.hpp +++ b/include/QtNodes/internal/NodeDelegateModel.hpp @@ -160,9 +160,9 @@ public Q_SLOTS: void dataUpdated(PortIndex const index); /** - * Tells the application that the output at `index` is no longer valid. - * The library does not listen to this signal: it does not propagate - * empty data downstream. Emit `dataUpdated` with a `nullptr` output for that. + * Tells the model that the output at `index` is no longer valid. + * `DataFlowGraphModel` sends empty data (`nullptr`) to the inputs that are + * connected to this output. */ void dataInvalidated(PortIndex const index); diff --git a/src/DataFlowGraphModel.cpp b/src/DataFlowGraphModel.cpp index fa8be2a7e..134438c72 100644 --- a/src/DataFlowGraphModel.cpp +++ b/src/DataFlowGraphModel.cpp @@ -65,6 +65,10 @@ void DataFlowGraphModel::connectDelegateModel(NodeId const nodeId, NodeDelegateM onOutPortDataUpdated(nodeId, portIndex); }); + connect(model, &NodeDelegateModel::dataInvalidated, [nodeId, this](PortIndex const portIndex) { + onOutPortDataInvalidated(nodeId, portIndex); + }); + connect(model, &NodeDelegateModel::portsAboutToBeDeleted, this, @@ -681,6 +685,18 @@ void DataFlowGraphModel::onOutPortDataUpdated(NodeId const nodeId, PortIndex con } } +void DataFlowGraphModel::onOutPortDataInvalidated(NodeId const nodeId, PortIndex const portIndex) +{ + // The output has no valid data. The connected inputs get no data. + std::unordered_set const &connected = connections(nodeId, + PortType::Out, + portIndex); + + for (auto const &cn : connected) { + propagateEmptyDataTo(cn.inNodeId, cn.inPortIndex); + } +} + void DataFlowGraphModel::propagateEmptyDataTo(NodeId const nodeId, PortIndex const portIndex) { QVariant emptyData{}; diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 36e9e1b93..a93ab3850 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -39,6 +39,7 @@ add_executable(test_nodes src/TestLockAndPaste.cpp src/TestGroupRepaint.cpp src/TestNotifications.cpp + src/TestDataInvalidated.cpp include/ApplicationSetup.hpp include/TestGraphModel.hpp include/UITestHelper.hpp diff --git a/test/src/TestDataInvalidated.cpp b/test/src/TestDataInvalidated.cpp new file mode 100644 index 000000000..3ceed3ac6 --- /dev/null +++ b/test/src/TestDataInvalidated.cpp @@ -0,0 +1,84 @@ +#include "ApplicationSetup.hpp" + +#include +#include +#include +#include + +#include + +#include + +using namespace QtNodes; + +namespace { + +class NumberData : public NodeData +{ +public: + NodeDataType type() const override { return {"number", "Number"}; } +}; + +class InvalidatingSource : public NodeDelegateModel +{ +public: + QString name() const override { return QStringLiteral("InvalidatingSource"); } + QString caption() const override { return QStringLiteral("Source"); } + unsigned int nPorts(PortType type) const override { return type == PortType::Out ? 1 : 0; } + NodeDataType dataType(PortType, PortIndex) const override { return NumberData{}.type(); } + void setInData(std::shared_ptr, PortIndex) override {} + std::shared_ptr outData(PortIndex) override { return std::make_shared(); } + QWidget *embeddedWidget() override { return nullptr; } +}; + +class RecordingSink : public NodeDelegateModel +{ +public: + QString name() const override { return QStringLiteral("RecordingSink"); } + QString caption() const override { return QStringLiteral("Sink"); } + unsigned int nPorts(PortType type) const override { return type == PortType::In ? 1 : 0; } + NodeDataType dataType(PortType, PortIndex) const override { return NumberData{}.type(); } + void setInData(std::shared_ptr data, PortIndex) override + { + received = data; + ++calls; + } + std::shared_ptr outData(PortIndex) override { return nullptr; } + QWidget *embeddedWidget() override { return nullptr; } + + std::shared_ptr received; + int calls = 0; +}; + +} // namespace + +TEST_CASE("dataInvalidated sends empty data to the inputs that are connected to the port", + "[dataflow][invalidated]") +{ + auto app = applicationSetup(); + + auto registry = std::make_shared(); + registry->registerModel(); + registry->registerModel(); + DataFlowGraphModel model(registry); + + NodeId const source = model.addNode(QStringLiteral("InvalidatingSource")); + NodeId const sink = model.addNode(QStringLiteral("RecordingSink")); + model.addConnection(ConnectionId{source, 0, sink, 0}); + + auto *sourceModel = model.delegateModel(source); + auto *sinkModel = model.delegateModel(sink); + + Q_EMIT sourceModel->dataUpdated(0); + REQUIRE(sinkModel->received != nullptr); + + int const callsBefore = sinkModel->calls; + Q_EMIT sourceModel->dataInvalidated(0); + + CHECK(sinkModel->calls == callsBefore + 1); + CHECK(sinkModel->received == nullptr); + + // Valid data flows again after an invalidation. + Q_EMIT sourceModel->dataUpdated(0); + CHECK(sinkModel->received != nullptr); +}