Global variables in user scripts

67 views
Skip to first unread message

Brian Theado

unread,
Sep 11, 2019, 7:28:39 AM9/11/19
to leo-editor
I'm writing a script button in which I want to transform some outline data into html and then display that html in a leo doc. The viewrendered functionality doesn't seem to really fit my needs as the render pane output is tied to whatever node is currently selected.

I just want to be able to display the html "on-demand" (i.e. through script button click) and refresh it on-demand.

I have working code for it, but it requires storing the dock object somewhere so it can be used again the next time the script is called. I was wondering if there is some good, already-established convention for storing "global" state for scripts.

In my case, the variable makes sense to be on a per-commander basis, so I just stored my information on the commander 'c'. That doesn't seem very clean to me and I was wondering if there is a better approach?

Here is my function which stores and uses global state on c:

def display_widget_in_leo_pane(c, w, name):
    """
        w is the widget to display
        name is the name the widget should appear in pane menu
    """
    dw = c.frame.top
    if not hasattr(c, 'my_docks'): c.my_docks = {}
    dock = c.my_docks.get(name)
    if not dock:
        dock = g.app.gui.create_dock_widget(
                 closeable=True, moveable=True, height=50, name=name)
        c.my_docks[name] = dock
        dw.addDockWidget(QtCore.Qt.RightDockWidgetArea, dock)
    dock.setWidget(w)
    dock.show()

And a function to use the above:

def display_html(html, name = 'test html'):
    w = QtWidgets.QTextBrowser()
    w.setHtml(html)
    display_widget_in_leo_pane(c, w, name)

Also, could someone comment on whether the above code is "leaking" widgets? Should I be calling dock.widget() to retrieve the old widget each time to perform some sort of delete/cleanup?

Brian

vitalije

unread,
Sep 11, 2019, 7:42:50 AM9/11/19
to leo-editor
You have c.user_dict for these kind of things. It is an ordinary python dictionary and you can put in it anything you want. Values you set in this dictionary will be there until Leo exits. If you need to make them more permanent then you can put values in c.db (looks like and behaves like a dictionary, but values must be pickleable).

Vitalije

Brian Theado

unread,
Sep 11, 2019, 8:23:56 AM9/11/19
to leo-editor
Thanks, Vitalije. Only after seeing your response did it occur to me to take a closer look at the scripting docs and of course the user_dict ivar is documented there.

--
You received this message because you are subscribed to the Google Groups "leo-editor" group.
To unsubscribe from this group and stop receiving emails from it, send an email to leo-editor+...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/leo-editor/39d49062-9e58-402d-9a97-bd98ed090441%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages