Borealis-Legacy/Experimental/experimental_nodes.py

103 lines
3.4 KiB
Python

#!/usr/bin/env python3
"""
Standalone NodeGraphQT Math Node Example
This example defines a custom "Math Node" that:
- Uses two text inputs for numeric operands (via add_text_input)
- Provides a combo box for operator selection (via add_combo_menu)
- Offers a checkbox to enable/disable the operation (via add_checkbox)
- Computes a result and updates its title accordingly.
"""
from NodeGraphQt import NodeGraph, BaseNode
class MathNode(BaseNode):
"""
Math Node:
- Operands: Two text inputs (Operand 1 and Operand 2)
- Operator: Combo box to select 'Add', 'Subtract', 'Multiply', or 'Divide'
- Enable: Checkbox to enable/disable the math operation
- Output: Result of the math operation (if enabled)
"""
__identifier__ = 'example.math'
NODE_NAME = 'Math Node'
def __init__(self):
super(MathNode, self).__init__()
# Add two text inputs for operands.
self.add_text_input('operand1', 'Operand 1', text='10')
self.add_text_input('operand2', 'Operand 2', text='5')
# Add a combo box for operator selection.
self.add_combo_menu('operator', 'Operator', items=['Add', 'Subtract', 'Multiply', 'Divide'])
# Add a checkbox to enable/disable the operation.
self.add_checkbox('enable', 'Enable Operation', state=True)
# Add an output port to transmit the result.
self.add_output('Result')
self.value = 0
self.set_name("Math Node")
self.process_input()
def process_input(self):
"""
Gather values from the widgets, perform the math operation if enabled,
update the node title, and send the result to connected nodes.
"""
try:
op1 = float(self.get_property('operand1'))
except (ValueError, TypeError):
op1 = 0.0
try:
op2 = float(self.get_property('operand2'))
except (ValueError, TypeError):
op2 = 0.0
operator = self.get_property('operator')
enable = self.get_property('enable')
if enable:
if operator == 'Add':
result = op1 + op2
elif operator == 'Subtract':
result = op1 - op2
elif operator == 'Multiply':
result = op1 * op2
elif operator == 'Divide':
result = op1 / op2 if op2 != 0 else 0.0
else:
result = 0.0
else:
result = 0.0
self.value = result
self.set_name(f"Result: {result}")
output_port = self.output(0)
if output_port and output_port.connected_ports():
for connected_port in output_port.connected_ports():
connected_node = connected_port.node()
if hasattr(connected_node, 'receive_data'):
connected_node.receive_data(result, source_port_name='Result')
if __name__ == '__main__':
import sys
try:
from PySide2.QtWidgets import QApplication
except ImportError:
from PySide6.QtWidgets import QApplication
app = QApplication(sys.argv)
graph = NodeGraph()
graph.register_node(MathNode)
node = graph.create_node('example.math.MathNode', name='Math Node')
node.set_pos(100, 100)
graph.widget.resize(1200, 800)
graph.widget.setWindowTitle("NodeGraphQT Math Node Demo")
graph.widget.show()
sys.exit(app.exec_())