r/OpenPythonSCAD • • 1d ago

Tutorial: Turn your PythonSCAD design into a class and get a real GUI form for its parameters

Most parametric designs end up as a function with a list of arguments, and after a while you can't remember what box(80, 50, 30, 2, True, False) actually means.

PythonSCAD has a small protocol for this. If you turn your design function into a class with three conventional methods, the editor shows a clickable calltip for it. Clicking the calltip opens your own PyQt6 dialog. When you press OK, the call in your script is rewritten with the new values.

We'll build this for a very simple box: length, width, height, wall thickness, and two checkboxes, hollow and notch (a finger notch in the front wall).

You need a Qt6 build of PythonSCAD. It ships PyQt6, so there's nothing extra to install.


Step 1: The design as a class

Normally you'd write def box(...). Instead we put the same code into __new__ of a class:

class box:
    def __new__(cls, length=80, width=50, height=30, wall=2,
                hollow=True, notch=False):
        body = cube([length, width, height])
        if hollow:
            cavity = cube([length - 2*wall, width - 2*wall, height])
            body -= cavity.translate([wall, wall, wall])
            if notch:
                cut = cylinder(r=height/4, h=wall*3, center=True, fn=48)
                body -= cut.rotate([90, 0, 0]).translate([length/2, wall/2, height])
        return body

Because __new__ can return any object, box(...) returns the geometry itself, not a box instance. For your scripts nothing changes: box(length=120).show() works just like a function call.

Step 2: get_calltip()

@staticmethod
def get_calltip():
    return "box(length, width, height, wall, hollow, notch)"

This is the text in the popup that appears when you type box(. Because the class also has on_editor_trigger, the popup is clickable and gets a ▶ marker.

Step 3: on_editor_trigger(pos) builds the dialog

This method runs when you click the calltip. pos marks the call in the editor, and you pass it on unchanged to two helper functions:

  • editor_get_call_args(pos) returns the current argument text

  • editor_replace_call_args(pos, text) replaces it

parse_arguments() from pyscadforms turns the argument text into a dict. That is how the form gets pre-filled with the values already in your code:

known, unknown = parse_arguments(box, editor_get_call_args(pos))

Two tiny helper functions create the fields:

def spin(name, default):
    w = QtWidgets.QDoubleSpinBox()
    w.setRange(0.5, 500)
    w.setValue(known.get(name, default))
    form.addRow(name, w)
    return w

length = spin("length", 80)
...
hollow = check("hollow", True)
notch  = check("notch", False)

Step 4: Things a plain parameter list can't do

Because this is a real Qt dialog, fields can react to each other. A notch only makes sense in a hollow box, and CubePreview (also from pyscadforms) draws a small 3D outline that follows the dimensions as you type:

def update():
    notch.setEnabled(hollow.isChecked())
    preview.set_size(length.value(), width.value(), height.value())

Step 5: Write the result back

if dialog.exec() == QtWidgets.QDialog.DialogCode.Accepted:
    parts = [f"length={length.value():g}", ..., f"notch={notch.isChecked()}"]
    parts += [f"{k}={v!r}" for k, v in unknown.items()]
    editor_replace_call_args(pos, ", ".join(parts))

:g turns 80.0 into 80. unknown holds arguments that aren't in the signature. They are written back instead of being silently dropped.

Step 6: Where the class has to live

The class must be loaded at startup and stay around for the whole session, which means .pythonscadrc or a library it imports. Save the code as boxform.py, for example in ~/pythonscad-lib/, and add this to .pythonscadrc (~/.config/PythonSCAD/ on Linux, ~/Library/Application Support/PythonSCAD on macOS, %LOCALAPPDATA%\PythonSCAD on Windows):

import sys, os
sys.path.insert(0, os.path.expanduser("~/pythonscad-lib"))

from pythonscad import *
from boxform import box

Then restart PythonSCAD, because .pythonscadrc is only read at startup.

Using it

New call: type box(, the calltip appears, click it, fill in the form, press OK. The line becomes

box(length=120, width=60, height=40, wall=2, hollow=True, notch=True).show()

Editing an existing line later: put the cursor anywhere between the parentheses of the box(...) call and press Ctrl+Shift+Space (on macOS Control+Shift+Space). The calltip comes back, and clicking it opens the form pre-filled with the current values.

If no calltip appears at all, check that autocompletion is switched on in the editor preferences. Calltips are tied to it.

Pitfalls

  • Don't define the class only in your script. That works only some of the time, depending on render order. Use .pythonscadrc.

  • Shadowing a built-in (e.g. your own cube class): save the original first (_native_cube = cube) and call _native_cube inside __new__, or it recurses into itself.

  • Qt5 builds have no PyQt. There you get the normal calltip, and box(...) still works as a plain function.

Full listing: boxform.py

"""boxform.py - a parametric box with an interactive PyQt6 form."""
from PyQt6 import QtWidgets, sip
from pythonscad import *
from pyscadforms import parse_arguments, CubePreview


class box:
    @staticmethod
    def get_calltip():
        return "box(length, width, height, wall, hollow, notch)"

    def __new__(cls, length=80, width=50, height=30, wall=2,
                hollow=True, notch=False):
        body = cube([length, width, height])
        if hollow:
            cavity = cube([length - 2*wall, width - 2*wall, height])
            body -= cavity.translate([wall, wall, wall])
            if notch:
                cut = cylinder(r=height/4, h=wall*3, center=True, fn=48)
                body -= cut.rotate([90, 0, 0]).translate([length/2, wall/2, height])
        return body

    @staticmethod
    def on_editor_trigger(pos):
        mw = sip.wrapinstance(mainwindow_ptr(), QtWidgets.QMainWindow)
        known, unknown = parse_arguments(box, editor_get_call_args(pos))

        dialog = QtWidgets.QDialog(mw)
        dialog.setWindowTitle("box")
        layout = QtWidgets.QHBoxLayout(dialog)
        form = QtWidgets.QFormLayout()
        layout.addLayout(form)
        preview = CubePreview(dialog)
        layout.addWidget(preview)

        def spin(name, default):
            w = QtWidgets.QDoubleSpinBox()
            w.setRange(0.5, 500)
            w.setValue(known.get(name, default))
            form.addRow(name, w)
            return w

        def check(name, default):
            w = QtWidgets.QCheckBox()
            w.setChecked(known.get(name, default))
            form.addRow(name, w)
            return w

        length = spin("length", 80)
        width = spin("width", 50)
        height = spin("height", 30)
        wall = spin("wall", 2)
        hollow = check("hollow", True)
        notch = check("notch", False)

        def update():
            notch.setEnabled(hollow.isChecked())   # a notch needs a hollow box
            preview.set_size(length.value(), width.value(), height.value())

        for w in (length, width, height):
            w.valueChanged.connect(update)
        hollow.toggled.connect(update)
        update()

        buttons = QtWidgets.QDialogButtonBox(
            QtWidgets.QDialogButtonBox.StandardButton.Ok
            | QtWidgets.QDialogButtonBox.StandardButton.Cancel
        )
        buttons.accepted.connect(dialog.accept)
        buttons.rejected.connect(dialog.reject)
        form.addRow(buttons)

        if dialog.exec() == QtWidgets.QDialog.DialogCode.Accepted:
            parts = [f"length={length.value():g}", f"width={width.value():g}",
                     f"height={height.value():g}", f"wall={wall.value():g}",
                     f"hollow={hollow.isChecked()}", f"notch={notch.isChecked()}"]
            parts += [f"{k}={v!r}" for k, v in unknown.items()]
            editor_replace_call_args(pos, ", ".join(parts))

Going further

The same pattern works for any design: a gear with module and tooth count, a hinge, or a polygon with a drawing canvas. That last one ships with PythonSCAD in pyscadforms.py and is a great place to look for more ideas. Docs: pythonscad.org → Development → "Extend Your Design with an Interactive Form".

See a demo at: https://www.youtube.com/watch?v=t5pk9XBUL_I

I'd love to see the forms you build. Post screenshots!

4 Upvotes

0 comments sorted by