Update live preview

Hi,

I’m creating my first addon, and not very familiar with the aqt library yet.

I created a script that updates a note by applying some simple transformations (e.g., lowercasing front and back cards). I can see the changes reflected in the editor (with editor.loadNote()) but not in the live preview.

def on_custom_action(editor: Editor):
    note = ensure_note(editor.note)
    backup_original_fields = {}

    for field_name in note.keys():
        backup_original_fields[field_name] = note[field_name]

    # Convert front and back of the note to lowercase
    for field_name in note.keys():
        current_content = note[field_name]
        transformed_content = current_content.lower()
        note[field_name] = transformed_content

    # Update the editor display to show the changes
    editor.loadNote()

    # Ask the user if they want to keep the changes
    if not askUser("Apply these changes to the note?"):
        # User rejected, restore original content
        for field_name, original_content in backup_original_fields.items():
            note[field_name] = original_content
        # Reload the editor with original content
        editor.loadNote()

How can I accomplish that?

try this

from aqt import mw
from aqt.qt import QAction
from aqt.utils import askUser, tooltip, showInfo
from aqt.editor import Editor
from aqt.gui_hooks import editor_did_load_note

_e = None

def lc(e):
    if not e or not e.note: return
    n, b = e.note, {}
    for k in n.keys(): b[k] = n[k]
    for k in n.keys():
        if n[k]: n[k] = n[k].lower()
    e.loadNote()
    if askUser("Apply?"):
        n.flush()
        tooltip("Transformed")
    else:
        for k in b: n[k] = b[k]
        e.loadNote()

a = QAction("Lowercase", mw)
a.triggered.connect(lambda: lc(_e) if _e and _e.note else showInfo("Open editor"))
mw.form.menuTools.addAction(a)
editor_did_load_note.append(lambda e: globals().update({"_e": e}))

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.