Skip to content

Graphics items

The QGraphicsItem classes that draw the scene. Applications rarely touch these directly, but they are the extension points for custom painting.

nodeeditor.node_graphics_node

A module containing Graphics representation of :class:~nodeeditor.node_node.Node

QDMGraphicsNodeLabel

Bases: QGraphicsTextItem

Single-line editable textbox floating above a QDMGraphicsNode.

Parented to the graphics node, so Qt moves it with the node for free. Click to focus/edit; Enter commits, Escape reverts, focus-out commits.

sanitize staticmethod

sanitize(text)

Force single-line plain text.

setLabelColors

setLabelColors(bg=None, border=None)

Set the background and border colors of the label box.

:param bg: background color of the label box :type bg: QColor :param border: border color of the label box :type border: QColor

focusInEvent

focusInEvent(event)

Remember the current text and switch the scene into editing mode.

:param event: Qt's focus event :type event: QFocusEvent

focusOutEvent

focusOutEvent(event)

Commit the edited text and leave editing mode.

:param event: Qt's focus event :type event: QFocusEvent

keyPressEvent

keyPressEvent(event)

Commit on Return/Enter, revert the text on Escape.

:param event: Qt's key event :type event: QKeyEvent

mousePressEvent

mousePressEvent(event)

Take the keyboard focus when the label is clicked.

:param event: Qt's mouse event :type event: QMouseEvent

mouseDoubleClickEvent

mouseDoubleClickEvent(event)

Select the whole text on a double click, so typing replaces it.

:param event: Qt's mouse event :type event: QMouseEvent

paint

paint(painter, option, widget=None)

Draw the rounded background box behind the label text.

QDMGraphicsNode

Bases: QGraphicsItem

Class describing Graphics representation of :class:~nodeeditor.node_node.Node

content property

content

Reference to Node Content

title property writable

title

title of this Node

:getter: current Graphics Node title :setter: stores and make visible the new title :type: str

initUI

initUI()

Set up this QGraphicsItem

initSizes

initSizes()

Set up internal attributes like width, height, etc.

initAssets

initAssets()

Initialize QObjects like QColor, QPen and QBrush

onSelected

onSelected()

Our event handling when the node was selected

doSelect

doSelect(new_state=True)

Safe version of selecting the Graphics Node. Takes care about the selection state flag used internally

:param new_state: True to select, False to deselect :type new_state: bool

mousePressEvent

mousePressEvent(event)

Keep the default Qt behavior, so the node can be moved and selected.

:param event: Qt's mouse event :type event: QMouseEvent

itemChange

itemChange(change, value)

Refresh this node's edges when Qt moves it.

Qt moves the dragged node - and every other node in the selection - itself. Reacting to the position change Qt already reports updates the edges of exactly the nodes that moved, replacing the old per-mouse-move scan of every node in the scene.

mouseMoveEvent

mouseMoveEvent(event)

Overridden event to detect that we moved with this Node

mouseReleaseEvent

mouseReleaseEvent(event)

Overriden event to handle when we moved, selected or deselected this Node

mouseDoubleClickEvent

mouseDoubleClickEvent(event)

Overriden event for doubleclick. Resend to Node::onDoubleClicked

hoverEnterEvent

hoverEnterEvent(event)

Handle hover effect

hoverLeaveEvent

hoverLeaveEvent(event)

Handle hover effect

boundingRect

boundingRect()

Defining Qt' bounding rectangle

initTitle

initTitle()

Set up the title Graphics representation: font, color, position, etc.

initContent

initContent()

Set up the grContent - QGraphicsProxyWidget to have a container for Graphics Content

initLabel

initLabel()

Create the floating single-line label above the node (hidden until text is set).

setLabelText

setLabelText(text)

Set label text (single-line). Empty text hides the label. No history stored.

labelText

labelText()

Return current label text.

setLabelVisible

setLabelVisible(visible)

Show/hide the label. Hidden when text is empty regardless.

isLabelVisible

isLabelVisible()

True while the label is requested visible and carries text.

setLabelOffset

setLabelOffset(offset)

Gap in px between node top and label bottom.

labelOffset

labelOffset()

Return the gap in px between node top and label bottom.

setLabelColor

setLabelColor(color)

Set the text color of the label.

:param color: the new text color :type color: QColor

setLabelFont

setLabelFont(font)

Set the font of the label and move the label to its new position.

:param font: the new font :type font: QFont

setLabelBackground

setLabelBackground(bg, border=None)

Set the background and border colors of the label box.

:param bg: background color of the label box :type bg: QColor :param border: border color of the label box :type border: QColor

setDetailState

setDetailState(state)

Apply a resolved per-element detail state.

The scene resolves its detail policy into a mapping of element key to "draw it" and hands the whole mapping over, so an application can add elements of its own to the same broadcast and read them back here. The zoom state itself rides along under the detail key.

Every child is pushed, not only the ones whose flag changed: a socket or a content proxy built after the last flip has never seen the state.

setDetailVisible

setDetailVisible(visible)

Show or hide this node's fine detail at low zoom.

The legacy entry point, kept for callers outside the scene: it drops the content widget, the floating label and the socket circles together. The scene uses :meth:setDetailState instead, which resolves each of those separately.

syncDetailVisibility

syncDetailVisibility()

Push the scene's current detail state onto every child item.

The sockets and the content proxy are built during Node.__init__, after Qt already reported this node joining the scene, so the scene's one-off broadcast never reached them - and Qt's ItemChildAddedChange hands over a base-class wrapper for an item still inside its own constructor, which has no setDetailVisible. Called from Node.__init__ once the node is fully built.

paint

paint(painter, QStyleOptionGraphicsItem, widget=None)

Painting the rounded rectanglar Node

nodeeditor.node_graphics_scene

A module containing Graphic representation of :class:~nodeeditor.node_scene.Scene

QDMGraphicsScene

Bases: QGraphicsScene

Class representing Graphic of :class:~nodeeditor.node_scene.Scene

showGrid property writable

showGrid

Get grid visibility state

Returns: bool: True if grid is visible, False otherwise

getGridColorLight

getGridColorLight()

Get the light grid color

setGridColorLight

setGridColorLight(color)

Set the light grid color

getGridColorDark

getGridColorDark()

Get the dark grid color

setGridColorDark

setGridColorDark(color)

Set the dark grid color

getBackgroundColor

getBackgroundColor()

Get the background color

setBackgroundColor

setBackgroundColor(color)

Set the background color

initAssets

initAssets()

Initialize QObjects like QColor, QPen and QBrush

dragMoveEvent

dragMoveEvent(event)

Overriden Qt's dragMoveEvent to enable Qt's Drag Events

setGrScene

setGrScene(width, height)

Set width and height of the Graphics Scene

updateDetailLod

updateDetailLod(scale)

Match the items' detail to scale; True when the state flipped.

Only a float comparison per frame; the broadcast to items runs once per flip. Callers must not be inside a paint pass - see :meth:setDetailLod.

setDetailLod

setDetailLod(visible)

Tell every item that cares whether the current zoom warrants detail.

Never call this while the scene is being painted. Hiding an item during a paint pass leaves the pixels it had already claimed on screen, and those ghosts then travel with the next scroll - which is why the view decides this before it paints rather than from drawBackground.

set_detail_policy

set_detail_policy(policy)

Say what each element may do when the canvas simplifies.

policy maps an element key to always, auto or never. auto follows the zoom threshold, always keeps the element at every zoom and never drops it at every zoom. Keys the library does not know are kept, so an application can register an element of its own and read the answer back with :meth:detail_enabled.

detail_enabled

detail_enabled(element)

Whether element should be drawn at the current zoom.

detail_state

detail_state()

The resolved per-element state, plus the zoom state under "detail".

drawBackground

drawBackground(painter, rect)

Draw background scene grid

nodeeditor.node_graphics_socket

A module containing Graphics representation of a :class:~nodeeditor.node_socket.Socket

QDMGraphicsSocket

Bases: QGraphicsItem

Class representing Graphic Socket in QGraphicsScene

socket_type property

socket_type

The socket's type, used to look up its color.

direction property

direction

+1 on an output socket, -1 on an input socket.

Shapes that must not flip (the chevron) simply ignore it.

getSocketColor

getSocketColor(key)

Returns the QColor for this key

changeSocketType

changeSocketType()

Change the Socket Type

setShape

setShape(name)

Draw this socket with the shape registered under name.

:param name: the registered shape name

initAssets

initAssets()

Initialize QObjects like QColor, QPen and QBrush

setText

setText(text)

Set the text to display inside socket

setDetailVisible

setDetailVisible(visible)

Show or hide this socket's circle at low zoom.

Pushed by the owning node when the scene drops to its level-of-detail state. A dozen sockets per node at normal zoom costs more per frame than the node itself; at that scale the circles are a couple of pixels wide and cannot be aimed at, so wiring is a zoomed-in activity.

paint

paint(painter, QStyleOptionGraphicsItem, widget=None)

Painting the socket shape and its label

shape

shape()

The outline used for hit testing.

What is drawn is what can be clicked: a click on a corner of a square socket misses it, exactly like a click beside a circle does.

boundingRect

boundingRect()

Defining Qt' bounding rectangle

hoverEnterEvent

hoverEnterEvent(event)

Handle hover effect

hoverLeaveEvent

hoverLeaveEvent(event)

Handle hover effect

nodeeditor.node_graphics_view

A module containing Graphics View for NodeEditor

QDMGraphicsView

Bases: QGraphicsView

Class representing NodeEditor's Graphics View

initUI

initUI()

Set up this QGraphicsView

isSnappingEnabled

isSnappingEnabled(event=None)

Returns True if snapping is currently enabled

resetMode

resetMode()

Helper function to re-set the grView's State Machine state to the default

dragEnterEvent

dragEnterEvent(event)

Trigger our registered Drag Enter events

dropEvent

dropEvent(event)

Trigger our registered Drop events

addDragEnterListener

addDragEnterListener(callback)

Register callback for Drag Enter event

:param callback: callback function

addDropListener

addDropListener(callback)

Register callback for Drop event

:param callback: callback function

mousePressEvent

mousePressEvent(event)

Dispatch Qt's mousePress event to corresponding function below

mouseReleaseEvent

mouseReleaseEvent(event)

Dispatch Qt's mouseRelease event to corresponding function below

middleMouseButtonPress

middleMouseButtonPress(event)

When Middle mouse button was pressed

middleMouseButtonRelease

middleMouseButtonRelease(event)

When Middle mouse button was released

leftMouseButtonPress

leftMouseButtonPress(event)

When Left mouse button was pressed

leftMouseButtonRelease

leftMouseButtonRelease(event)

When Left mouse button was released

rightMouseButtonPress

rightMouseButtonPress(event)

When Right mouse button was pressed

rightMouseButtonRelease

rightMouseButtonRelease(event)

When Right mouse button was release

mouseMoveEvent

mouseMoveEvent(event)

Overriden Qt's mouseMoveEvent handling Scene/View logic

keyPressEvent

keyPressEvent(event)

.. note:: This overridden Qt's method was used for handling key shortcuts, before we implemented proper QWindow with Actions and Menu. Still the commented code serves as an example on how to handle key presses without Qt's framework for Actions and shortcuts. There is also an example on how to solve the problem when a Node contains Text/LineEdit and we press the Delete key (also serving to delete Node)

:param event: Qt's Key event :type event: QKeyEvent :return:

cutIntersectingEdges

cutIntersectingEdges()

Compare which Edges intersect with current Cut line and delete them safely

setSocketHighlights

setSocketHighlights(scenepos, highlighted=True, radius=50)

Set/disable socket highlights in Scene area defined by scenepos and radius

deleteSelected

deleteSelected()

Delete selected items. Delete-key on a Group = delete Group + Children.

debug_modifiers

debug_modifiers(event)

Helper function get string if we hold Ctrl, Shift or Alt modifier keys

getItemAtClick

getItemAtClick(event)

Return the object on which we've clicked/release mouse button

:param event: Qt's mouse or key event :type event: QEvent :return: QGraphicsItem which the mouse event happened or None

distanceBetweenClickAndReleaseIsOff

distanceBetweenClickAndReleaseIsOff(event)

Measures if we are too far from the last Mouse button click scene position. This is used for detection if we release too far after we clicked on a Socket

:param event: Qt's mouse event :type event: QMouseEvent :return: True if we released too far from where we clicked before

zoomIn

zoomIn()

Step the zoom level up and return the factor to scale the scene by.

:return: the zoom factor to apply :rtype: float

zoomOut

zoomOut()

Step the zoom level down and return the factor to scale the scene by.

:return: the zoom factor to apply :rtype: float

applyZoom

applyZoom(zoomFactor)

Scale the scene by zoomFactor, keeping the zoom level inside the configured range.

:param zoomFactor: the factor to scale the scene by :type zoomFactor: float

paintEvent

paintEvent(event)

Sync the level of detail with the zoom, then paint the scene.

wheelEvent

wheelEvent(event)

overridden Qt's wheelEvent. This handles zooming

nodeeditor.node_graphics_edge

A module containing the Graphics representation of an Edge

QDMGraphicsEdge

Bases: QGraphicsPathItem

Base class for Graphics Edge

initUI

initUI()

Set up this QGraphicsPathItem

initAssets

initAssets()

Initialize QObjects like QColor, QPen and QBrush

createEdgePathCalculator

createEdgePathCalculator()

Create instance of :class:~nodeeditor.node_graphics_edge_path.GraphicsEdgePathBase

determineEdgePathClass

determineEdgePathClass()

Decide which GraphicsEdgePath class should be used to calculate path according to edge.edge_type value

makeUnselectable

makeUnselectable()

Used for drag edge to disable click detection over this graphics item

changeColor

changeColor(color)

Change color of the edge from string hex value '#00ff00'

setColorFromSockets

setColorFromSockets()

Change color according to connected sockets. Returns True if color can be determined

label

label()

Return the current code-set edge label ("" when unset).

setLabel

setLabel(text)

Set the text drawn on top of the edge.

Code-only API: the label item is not selectable, movable, focusable and accepts no mouse buttons, so users cannot edit it directly.

:param text: label text, ""/None hides the label

setLabelColor

setLabelColor(color)

Set label text color from QColor or hex string.

setLabelFont

setLabelFont(font)

Set label font, then recenter it on the edge path.

setLabelOffset

setLabelOffset(x, y)

Offset (in px) applied to the centered label position.

updateLabelPosition

updateLabelPosition()

Center the label on top of the current edge path.

onSelected

onSelected()

Our event handling when the edge was selected

doSelect

doSelect(new_state=True)

Safe version of selecting the Graphics Node. Takes care about the selection state flag used internally

:param new_state: True to select, False to deselect :type new_state: bool

mouseReleaseEvent

mouseReleaseEvent(event)

Overridden Qt's method to handle selecting and deselecting this Graphics Edge

hoverEnterEvent

hoverEnterEvent(event)

Handle hover effect

:param event: The hover event :type event: Optional[QGraphicsSceneHoverEvent]

hoverLeaveEvent

hoverLeaveEvent(event)

Handle hover effect

:param event: The hover event :type event: Optional[QGraphicsSceneHoverEvent]

setSource

setSource(x, y)

Set source point

:param x: x position :type x: float :param y: y position :type y: float

setDestination

setDestination(x, y)

Set destination point

:param x: x position :type x: float :param y: y position :type y: float

setPositions

setPositions(source, destination)

Set both ends and adopt the resulting path once.

A node move changes both ends. Adopting inside each setter would run the route calculation twice per edge per move, and that calculation is the expensive part of moving a node.

:param source: new source point :param destination: new destination point

adoptGeometry

adoptGeometry()

Recompute the drawn path right away, so Qt invalidates the true rect.

The setters run before the caller repaints, and a path picked up only while painting invalidates the previous geometry (see :meth:refreshPath).

strokeMargin

strokeMargin()

Half the widest pen this edge can paint with, plus an antialias pixel.

paint strokes the path, and a stroke reaches half its width past the path on both sides. A boundingRect of the bare path is therefore smaller than what the item draws, and every repaint leaves the outer band of the previous stroke on screen. That is not a one-pixel cosmetic miss: while a node is dragged, each frame adds a band along the path's old position, and dozens of frames accumulate into the smeared arcs and loops the canvas was showing.

boundingRect

boundingRect()

Defining Qt' bounding rectangle (path united with label rect).

refreshPath

refreshPath()

Adopt the current path and label position now.

Qt invalidates an item by its declared geometry, so an item that only adopts a new path while painting invalidates the previous one and draws the new one: whatever the old path covered outside both rectangles stays on screen. Callers that know the edge moved (updatePositions) call this first, which makes setPath repaint the union of old and new.

shape

shape()

Returns QPainterPath representation of this Edge

:return: path representation :rtype: QPainterPath

paint

paint(painter, QStyleOptionGraphicsItem, widget=None)

Qt's overridden method to paint this Graphics Edge. Path calculated in :func:~nodeeditor.node_graphics_edge.QDMGraphicsEdge.calcPath method

intersectsWith

intersectsWith(p1, p2)

Does this Graphics Edge intersect with the line between point A and point B ?

:param p1: point A :type p1: QPointF :param p2: point B :type p2: QPointF :return: True if this Graphics Edge intersects :rtype: bool

calcPath

calcPath()

Will handle drawing QPainterPath from Point A to B. Internally there exist self.pathCalculator which is an instance of derived :class:~nodeeditor.node_graphics_edge_path.GraphicsEdgePathBase class containing the actual calcPath() function - computing how the edge should look like.

:returns: QPainterPath of the edge connecting source and destination :rtype: QPainterPath

nodeeditor.node_graphics_edge_path

A module containing the classes that calculate the graphics path drawn for an Edge.

Every class derives from :class:GraphicsEdgePathBase and implements :meth:GraphicsEdgePathBase.calcPath, which turns the positions of the edge's two sockets into the :class:~qtpy.QtGui.QPainterPath that gets painted.

GraphicsEdgePathBase

Base Class for calculating the graphics path to draw for an graphics Edge

calcPath

calcPath()

Calculate the Direct line connection

:returns: QPainterPath of the graphics path to draw :rtype: QPainterPath or None

GraphicsEdgePathDirect

Bases: GraphicsEdgePathBase

Direct line connection Graphics Edge

calcPath

calcPath()

Calculate the Direct line connection

:returns: QPainterPath of the direct line :rtype: QPainterPath

GraphicsEdgePathBezier

Bases: GraphicsEdgePathBase

Cubic line connection Graphics Edge

calcPath

calcPath()

Calculate the cubic Bezier line connection with 2 control points

:returns: QPainterPath of the cubic Bezier line :rtype: QPainterPath

GraphicsEdgePathSquare

Bases: GraphicsEdgePathBase

Square line connection Graphics Edge

calcPath

calcPath()

Calculate the square edge line connection

:returns: QPainterPath of the edge square line :rtype: QPainterPath

GraphicsEdgePathImprovedSharp

Bases: GraphicsEdgePathBase

Better Cubic line connection Graphics Edge

calcPath

calcPath()

Calculate the Direct line connection

:returns: QPainterPath of the painting line :rtype: QPainterPath

GraphicsEdgePathImprovedBezier

Bases: GraphicsEdgePathBase

Better Cubic line connection Graphics Edge

calcPath

calcPath()

Calculate the Direct line connection

:returns: QPainterPath of the painting line :rtype: QPainterPath

nodeeditor.node_graphics_cutline

A module containing the class for Cutting Line

QDMCutLine

Bases: QGraphicsItem

Class representing Cutting Line used for cutting multiple Edges with one stroke

boundingRect

boundingRect()

Defining Qt' bounding rectangle

shape

shape()

Calculate the QPainterPath object from list of line points

:return: shape function returning QPainterPath representation of Cutting Line :rtype: QPainterPath

paint

paint(painter, QStyleOptionGraphicsItem, widget=None)

Paint the Cutting Line