Writing a User Plugin

A user plugin is simply a python code module, placed in an appropriate location. Here is an example of creating a simple hello plugin and getting it loaded by the application.

First, create a directory to store your user plugins, such as a TRPlugins directory underneath your Documents directory. You’ll then need to ensure that directory is listed in the plugins=[] list in the directories section of the Configuration File.

[directories]
# Default directory to find data files
data = "/home/patrick/Documents/TRData"
# List of directories containing user plugin modules
plugins = ["/home/patrick/Documents/TRPlugins"]

On Windows, the directory might be something like C:\Users\Patrick\Documents\TRPlugins instead. To get the plugin to load, include its name in the list of plugins in the load=[] list of the [plugins] section of the configuration file.

[plugins]
# List of plugin modules to load
load = ["aligncam", "scope", "delay", "chopper", "detector", "interface", "acquisition", "hello"]

Create a file in the TRPlugins directory named hello.py and open it in your favourite code editor. Type, or copy/paste the following code snippet, then save the file.

# It's a good idea to use python's logging facilities
import logging

# We'll want to make a Qt message box, so import it now
from PySide6.QtWidgets import QMessageBox

# The trspectrometer package will be in the python path, so
# import the configuration module to get access to the configuration file etc
import configuration as config

log = logging.getLogger(__name__)
log.info("Hello, World!")

# The configuration module stores a reference to the MainWindow object. This is the top-level GUI
# element, which can then be used to tweak any part of the application interface.
mw = config.mainwindow

def say_hello():
    """Pop up a "Hello, World!" message box."""
    QMessageBox.information(mw, "Hello", "Hello, World!")

# Add a "Hello" action to the "View" menu, connect it to our say_hello function
hello_action = mw.menuView.addAction("Hello")
hello_action.triggered.connect(say_hello)

Load up the TRSpectrometer application, then check the log (View->Log menu), where you should be able to find the following lines during startup.

INFO:trspectrometer.mainwindow:Loading plugin module: hello
INFO:hello:Hello, World!

You should also see a new item in the View menu (View->Hello), selecting it should pop up a dialog box.

Congratulations, you’ve just written a plugin! To see how more complicated plugins can be built, see the API Documentation under the plugins package, where the built-in plugins are listed. The code for every plugin can be viewed and may be used as a base for new plugins.