Skip to content

Control Panel

ControlPanel(theme_manager=None)

Bases: QWidget

Main control panel widget for managing plot axes and curves.

This widget provides the primary interface for adding, configuring, and managing plot axes and their associated curves. It includes functionality for PV search, formula creation, and curve management.

Parameters:

Name Type Description Default
theme_manager ThemeManager

The theme manager for handling UI theming

None
Source code in trace/widgets/control_panel.py
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
def __init__(self, theme_manager: ThemeManager = None):
    """Initialize the control panel.

    Parameters
    ----------
    theme_manager : ThemeManager, optional
        The theme manager for handling UI theming
    """
    super().__init__()
    self.theme_manager = theme_manager
    self.setLayout(QtWidgets.QVBoxLayout())
    # self.setStyleSheet("background-color: white;")

    self._curve_dict = {}
    self.key_gen = self._generate_curve_key()
    next(self.key_gen)  # Prime the generator

    self.curve_palette = "default"
    if self.theme_manager:
        self.theme_manager.theme_changed.connect(self.on_theme_changed)

    # Create pv plotter layout
    pv_plotter_layout = QtWidgets.QHBoxLayout()
    self.layout().addLayout(pv_plotter_layout)
    self.search_button = QtWidgets.QPushButton()
    self.search_button.setFlat(True)
    self.search_button.clicked.connect(self.search_pv)
    pv_plotter_layout.addWidget(self.search_button)

    self.calc_button = QtWidgets.QPushButton()
    self.calc_button.setFlat(True)
    self.calc_button.clicked.connect(self.show_formula_dialog)
    pv_plotter_layout.addWidget(self.calc_button)

    self.pv_line_edit = QtWidgets.QLineEdit()
    self.pv_line_edit.setPlaceholderText("Enter PV")
    self.pv_line_edit.returnPressed.connect(self.add_curve_from_line_edit)
    pv_plotter_layout.addWidget(self.pv_line_edit)
    pv_plot_button = QtWidgets.QPushButton("Plot")
    pv_plot_button.clicked.connect(self.add_curve_from_line_edit)
    pv_plotter_layout.addWidget(pv_plot_button)

    # Style the plot button with blue accent color
    if self.theme_manager:
        blue_color = self.theme_manager.get_icon_color(IconColors.ACCENT)
        text_color = "#FFFFFF"
        pv_plot_button.setStyleSheet(
            f"""
            QPushButton {{
                background-color: {blue_color};
                color: {text_color};
            }}
        """
        )

    self.axis_list = QtWidgets.QVBoxLayout()
    frame = QtWidgets.QFrame()
    frame.setLayout(self.axis_list)
    scrollarea = QtWidgets.QScrollArea()
    scrollarea.setWidgetResizable(True)
    scrollarea.setWidget(frame)
    self.layout().addWidget(scrollarea)
    self.axis_list.addStretch()

    new_axis_button = QtWidgets.QPushButton("New Axis")
    new_axis_button.clicked.connect(self.add_empty_axis)
    self.layout().addWidget(new_axis_button)

    self.archive_search = ArchiveSearchWidget()
    self.archive_search.append_PVs_requested.connect(self.add_curves)

    self.formula_dialog = FormulaDialog(self)
    self.formula_dialog.formula_accepted.connect(self.handle_formula_accepted)
    self.curve_list_changed.connect(self.formula_dialog.curve_model.refresh)

    self.update_icons()
    QTimer.singleShot(0, self.pv_line_edit.setFocus)

plot property writable

Get the associated plot widget.

curve_dict property

Return dictionary of curves with PV keys.

curve_item_dict property

Returns dictionary of curves on plot with associated pvname, axisItem, and curveItem

update_icons()

Update all icons based on current theme.

Source code in trace/widgets/control_panel.py
117
118
119
120
121
122
123
124
125
def update_icons(self) -> None:
    """Update all icons based on current theme."""
    if self.theme_manager:
        calc_icon = self.theme_manager.create_icon("fa6s.calculator", IconColors.PRIMARY)
        if calc_icon:
            self.calc_button.setIcon(calc_icon)
        search_icon = self.theme_manager.create_icon("fa6s.magnifying-glass", IconColors.PRIMARY)
        if search_icon:
            self.search_button.setIcon(search_icon)

on_theme_changed(theme)

Handle theme changes by updating icons.

Parameters:

Name Type Description Default
theme Theme

The new theme, unused

required
Source code in trace/widgets/control_panel.py
127
128
129
130
131
132
133
134
135
def on_theme_changed(self, theme: Theme) -> None:
    """Handle theme changes by updating icons.

    Parameters
    ----------
    theme : Theme
        The new theme, unused
    """
    self.update_icons()

minimumSizeHint()

Return the minimum size hint for the control panel.

Source code in trace/widgets/control_panel.py
137
138
139
140
141
def minimumSizeHint(self) -> QtCore.QSize:
    """Return the minimum size hint for the control panel."""
    inner_size = self.axis_list.minimumSize()
    buffer = self.pv_line_edit.font().pointSize() * 3
    return QtCore.QSize(inner_size.width() + buffer, inner_size.height())

add_curve_from_line_edit()

Add a curve from the PV line edit input.

Source code in trace/widgets/control_panel.py
143
144
145
146
147
def add_curve_from_line_edit(self) -> None:
    """Add a curve from the PV line edit input."""
    pv = self.pv_line_edit.text()
    self.add_curve(pv)
    self.pv_line_edit.clear()

search_pv()

Show or activate the PV search widget.

Source code in trace/widgets/control_panel.py
170
171
172
173
174
175
176
def search_pv(self) -> None:
    """Show or activate the PV search widget."""
    if not self.archive_search.isVisible():
        self.archive_search.show()
    else:
        self.archive_search.raise_()
        self.archive_search.activateWindow()

show_formula_dialog()

Show the formula dialog pop-up.

Source code in trace/widgets/control_panel.py
178
179
180
181
182
183
184
def show_formula_dialog(self):
    """Show the formula dialog pop-up."""
    if not hasattr(self, "formula_dialog") or not self.formula_dialog.isVisible():
        self.formula_dialog.show()
    else:
        self.formula_dialog.raise_()
        self.formula_dialog.activateWindow()

handle_formula_accepted(formula)

Handle the formula accepted from the formula dialog.

Parameters:

Name Type Description Default
formula str

The accepted formula string

required
Source code in trace/widgets/control_panel.py
186
187
188
189
190
191
192
193
194
195
196
@QtCore.Slot(str)
def handle_formula_accepted(self, formula: str) -> None:
    """Handle the formula accepted from the formula dialog.

    Parameters
    ----------
    formula : str
        The accepted formula string
    """
    self.add_curve(formula)
    self.cleanup_duplicate_curves()

cleanup_duplicate_curves()

Remove duplicate entries in curve dictionary.

Source code in trace/widgets/control_panel.py
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
def cleanup_duplicate_curves(self) -> None:
    """Remove duplicate entries in curve dictionary."""
    seen_curves = {}
    to_remove = []

    for key, curve in self._curve_dict.items():
        curve_id = id(curve)
        if curve_id in seen_curves:
            to_remove.append(key)
        else:
            seen_curves[curve_id] = key

    for key in to_remove:
        del self._curve_dict[key]

    if to_remove:
        self.curve_list_changed.emit()

add_curves(pvs)

Add multiple curves from a list of PV names.

Parameters:

Name Type Description Default
pvs list[str]

List of PV names to add as curves

required
Source code in trace/widgets/control_panel.py
243
244
245
246
247
248
249
250
251
252
def add_curves(self, pvs: list[str]) -> None:
    """Add multiple curves from a list of PV names.

    Parameters
    ----------
    pvs : list[str]
        List of PV names to add as curves
    """
    for pv in pvs:
        self.add_curve(pv)

add_axis_item(axis)

Add an existing AxisItem to the plot.

Source code in trace/widgets/control_panel.py
267
268
269
270
271
272
273
274
275
276
def add_axis_item(self, axis: BasePlotAxisItem) -> "AxisItem":
    """Add an existing AxisItem to the plot."""
    self.match_axis_tick_font(axis)
    axis_item = AxisItem(axis, control_panel=self, theme_manager=self.theme_manager)
    axis_item.curves_list_changed.connect(self.curve_list_changed.emit)
    self.axis_list.insertWidget(self.axis_list.count() - 1, axis_item)
    logger.debug(f"Added axis {axis.name} to plot")
    self.updateGeometry()

    return axis_item

match_axis_tick_font(axis)

Matches the axis' tick font to the X-Axis of the plot. Only necessary if the user has changed the tick font of the plot's axes.

Parameters:

Name Type Description Default
axis BasePlotAxisItem

The axis to match the tick font for.

required
Source code in trace/widgets/control_panel.py
278
279
280
281
282
283
284
285
286
287
288
def match_axis_tick_font(self, axis: BasePlotAxisItem) -> None:
    """Matches the axis' tick font to the X-Axis of the plot. Only necessary
    if the user has changed the tick font of the plot's axes.

    Parameters
    ----------
    axis : BasePlotAxisItem
        The axis to match the tick font for."""
    x_axis = self.plot.getAxis("bottom")
    if x_axis is not None:
        axis.setTickFont(x_axis.style["tickFont"])

get_axis_item(axis_name)

Get an AxisItem by its name.

Source code in trace/widgets/control_panel.py
290
291
292
293
294
295
296
def get_axis_item(self, axis_name: str) -> "AxisItem":
    """Get an AxisItem by its name."""
    for index in range(self.axis_list.count()):
        item = self.axis_list.itemAt(index).widget()
        if isinstance(item, AxisItem) and item.name == axis_name:
            return item
    return None

get_last_axis_item()

Get the last AxisItem in the list.

Source code in trace/widgets/control_panel.py
298
299
300
301
302
303
304
def get_last_axis_item(self) -> "AxisItem":
    """Get the last AxisItem in the list."""
    if self.axis_list.count() > 1:  # the stretch makes count >= 1
        return self.axis_list.itemAt(self.axis_list.count() - 2).widget()
    else:
        logger.warning("No axes available to return the last AxisItem.")
        return None

set_curve_palette(palette_name, apply=False)

Set the default palette for new curves.

Parameters: palette_name (str): name of selected palette apply (bool): If true, apply palette to exiting curves

Source code in trace/widgets/control_panel.py
306
307
308
309
310
311
312
313
314
315
316
317
318
319
def set_curve_palette(self, palette_name: str, apply: bool = False) -> None:
    """
    Set the default palette for new curves.

    Parameters:
        palette_name (str): name of selected palette
        apply (bool): If true, apply palette to exiting curves
    """
    self.curve_palette = palette_name
    if apply:
        for index, curve in enumerate(self.curve_item_dict.keys()):
            color = ColorButton.index_color(index, palette=self.curve_palette)
            curve.color = color
            self.curve_item_dict[curve]["curveItem"].on_color_changed(color)

clear_all()

Clear all axes and curves from the plot and control panel.

Source code in trace/widgets/control_panel.py
358
359
360
361
362
363
def clear_all(self) -> None:
    """Clear all axes and curves from the plot and control panel."""
    logger.debug("Clearing all axes and curves from the plot")
    while self.axis_list.count() > 1:  # Keep the stretch at the end
        self.axis_list.itemAt(0).widget().close()
    self.plot.redrawPlot()

clear_curves()

Clear all curves from the plot and control panel.

Source code in trace/widgets/control_panel.py
365
366
367
368
369
370
def clear_curves(self) -> None:
    """Clear all curves from the plot and control panel."""
    logger.debug("Clearing all curves from the plot")
    for axis_item in self.axis_list:
        if isinstance(axis_item, AxisItem):
            axis_item.clear_curves()

set_axes(axes=None)

Given a list of dictionaries containing axis data, clear the plot's axes, and set all new axes based on the provided axis data.

Parameters:

Name Type Description Default
axes List[Dict]

Axis properties to be set for all new axes on the plot

None
Source code in trace/widgets/control_panel.py
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
def set_axes(self, axes: list[dict] = None) -> None:
    """Given a list of dictionaries containing axis data, clear the
    plot's axes, and set all new axes based on the provided axis data.

    Parameters
    ----------
    axes : List[Dict]
        Axis properties to be set for all new axes on the plot
    """
    self.clear_all()
    for axis in axes:
        self.plot.addAxis(
            plot_data_item=None,
            name=axis["name"],
            orientation=axis.get("orientation", "left"),
            label=axis["name"],
            log_mode=axis.get("logMode", False),
        )
        # Convert axis properties to match BasePlotAxisItem
        new_axis = self.plot._axes[-1]
        new_axis.setLabel(axis["name"], color="black")

        new_axis_item = self.add_axis_item(new_axis)
        if "minRange" in axis:
            new_axis_item.set_min_range(axis["minRange"])
        if "maxRange" in axis:
            new_axis_item.set_max_range(axis["maxRange"])
        if "autoRange" in axis:
            new_axis_item.auto_range_checkbox.setChecked(axis["autoRange"])

set_curves(curves=None)

Given a list of dictionaries containing curve data, clear the plot's curves, and set all new curves based on the provided curve data.

Parameters:

Name Type Description Default
curves List[Dict]

Curve properties to be set for all new curves on the plot

None
Source code in trace/widgets/control_panel.py
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
def set_curves(self, curves: list[dict] = None) -> None:
    """Given a list of dictionaries containing curve data, clear the
    plot's curves, and set all new curves based on the provided curve data.

    Parameters
    ----------
    curves : List[Dict]
        Curve properties to be set for all new curves on the plot
    """
    for curve_dict in curves:
        try:
            axis_name = curve_dict.get("yAxisName", "Y-Axis 0")
            axis_item = self.get_axis_item(axis_name)
        except KeyError:
            axis_item = self.get_last_axis_item()

        if axis_item is None:
            axis_item = self.add_empty_axis(axis_name)

        if "channel" in curve_dict:
            pv_name = curve_dict.get("channel", "")
            del curve_dict["channel"]  # Remove channel key to avoid conflicts with y_channel
            axis_item.add_curve(pv_name, curve_dict)
        elif "formula" in curve_dict:
            formula = curve_dict.get("formula", "f://")
            axis_item.add_formula_curve(formula)
    self.plot.redrawPlot()
    self.axis_list.itemAt(self.axis_list.count() - 2).widget()

move_curve_to_axis(curve_item, target_axis_name)

Remove a given CurveItem from its current AxisItem and add it to the AxisItem with the given target axis name. If no such AxisItem exists, a new one will be created. Intended to be used for Axes named after a curve's unit.

Parameters:

Name Type Description Default
curve_item CurveItem

CurveItem to be moved to a new axis.

required
target_axis_name str

Name of the target axis to move the CurveItem to.

required
Source code in trace/widgets/control_panel.py
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
def move_curve_to_axis(self, curve_item: "CurveItem", target_axis_name: str) -> None:
    """Remove a given CurveItem from its current AxisItem and add it to
    the AxisItem with the given target axis name. If no such AxisItem
    exists, a new one will be created. Intended to be used for Axes
    named after a curve's unit.

    Parameters
    ----------
    curve_item : CurveItem
        CurveItem to be moved to a new axis.
    target_axis_name : str
        Name of the target axis to move the CurveItem to.
    """
    axis_item = self.get_axis_item(target_axis_name)
    if axis_item is None:
        axis_item = self.add_empty_axis(target_axis_name)

    old_axis_item = curve_item.axis_item
    old_axis_item.remove_curve_item(curve_item)
    axis_item.add_curve_item(curve_item)

AxisItem(plot_axis_item, control_panel=None, theme_manager=None)

Bases: QWidget

Widget for managing a single plot axis and its associated curves.

This widget provides controls for axis configuration including name, range, auto-scaling, and curve management. It supports drag-and-drop for curve reordering and moving curves between axes.

Parameters:

Name Type Description Default
plot_axis_item BasePlotAxisItem

The plot axis item to manage

required
control_panel ControlPanel

Reference to the parent control panel

None
theme_manager ThemeManager

The theme manager for UI theming

None
Source code in trace/widgets/control_panel.py
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
def __init__(
    self, plot_axis_item: BasePlotAxisItem, control_panel: ControlPanel = None, theme_manager: ThemeManager = None
):
    """Initialize the axis item widget.

    Parameters
    ----------
    plot_axis_item : BasePlotAxisItem
        The plot axis item to manage
    control_panel : ControlPanel, optional
        Reference to the parent control panel
    theme_manager : ThemeManager, optional
        The theme manager for UI theming
    """
    super().__init__()
    self.source = plot_axis_item
    self.control_panel_ref = control_panel
    self.theme_manager = theme_manager
    self.setLayout(QtWidgets.QVBoxLayout())
    self.setAcceptDrops(True)

    if self.theme_manager:
        self.theme_manager.theme_changed.connect(self.on_theme_changed)

    self.header_layout = QtWidgets.QHBoxLayout()
    self.layout().addLayout(self.header_layout)

    self._expanded = False
    self.expand_button = QtWidgets.QPushButton()
    self.expand_button.setFlat(True)
    self.expand_button.clicked.connect(self.toggle_expand)
    self.header_layout.addWidget(self.expand_button)

    layout = QtWidgets.QVBoxLayout()
    self.header_layout.addLayout(layout)
    self.top_settings_layout = QtWidgets.QHBoxLayout()
    layout.addLayout(self.top_settings_layout)
    self.axis_label = QtWidgets.QLineEdit()
    self.axis_label.setText(self.source.name)
    self.axis_label.editingFinished.connect(self.set_axis_name)
    self.axis_label.returnPressed.connect(self.axis_label.clearFocus)
    self.top_settings_layout.addWidget(self.axis_label)
    self.settings_button = QtWidgets.QPushButton()
    self.settings_button.setFlat(True)
    self.settings_modal = None
    self.settings_button.clicked.connect(self.show_settings_modal)
    self.top_settings_layout.addWidget(self.settings_button)
    self.delete_button = QtWidgets.QPushButton()
    self.delete_button.setFlat(True)
    self.delete_button.clicked.connect(self.close)
    self.top_settings_layout.addWidget(self.delete_button)
    self.bottom_settings_layout = QtWidgets.QHBoxLayout()
    layout.addLayout(self.bottom_settings_layout)
    self.auto_range_checkbox = QtWidgets.QCheckBox("Auto")
    self.auto_range_checkbox.setCheckState(QtCore.Qt.Checked if self.source.auto_range else QtCore.Qt.Unchecked)
    self.auto_range_checkbox.stateChanged.connect(self.set_auto_range)
    self.source.linkedView().sigRangeChangedManually.connect(self.disable_auto_range)
    self.bottom_settings_layout.addWidget(self.auto_range_checkbox)
    self.bottom_settings_layout.addWidget(QtWidgets.QLabel("min, max"))
    self.min_range_line_edit = QtWidgets.QLineEdit()
    self.min_range_line_edit.editingFinished.connect(self.set_min_range)
    self.min_range_line_edit.editingFinished.connect(self.disable_auto_range)
    self.min_range_line_edit.setMinimumWidth(self.min_range_line_edit.font().pointSize() * 8)
    self.bottom_settings_layout.addWidget(self.min_range_line_edit)
    self.bottom_settings_layout.addWidget(QtWidgets.QLabel(","))
    self.max_range_line_edit = QtWidgets.QLineEdit()
    self.max_range_line_edit.editingFinished.connect(self.set_max_range)
    self.max_range_line_edit.editingFinished.connect(self.disable_auto_range)
    self.max_range_line_edit.setMinimumWidth(self.max_range_line_edit.font().pointSize() * 8)
    self.bottom_settings_layout.addWidget(self.max_range_line_edit)
    self.source.sigYRangeChanged.connect(self.handle_range_change)

    self.active_toggle = ToggleSwitch("Active")
    self.active_toggle.setCheckState(QtCore.Qt.Checked if self.source.isVisible() else QtCore.Qt.Unchecked)
    self.active_toggle.stateChanged.connect(self.set_active)
    self.header_layout.addWidget(self.active_toggle)

    self.placeholder = QtWidgets.QWidget(self)
    self.placeholder.hide()
    self.placeholder.setStyleSheet("background-color: lightgrey;")

    self.update_icons()

name property

Get the name of the axis.

update_icons()

Update all icons based on current theme

Source code in trace/widgets/control_panel.py
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
def update_icons(self):
    """Update all icons based on current theme"""
    if self.theme_manager:
        if self._expanded:
            expand_icon = self.theme_manager.create_icon("msc.chevron-down", IconColors.PRIMARY)
        else:
            expand_icon = self.theme_manager.create_icon("msc.chevron-right", IconColors.PRIMARY)

        if expand_icon:
            self.expand_button.setIcon(expand_icon)

        settings_icon = self.theme_manager.create_icon("msc.settings-gear", IconColors.PRIMARY)
        if settings_icon:
            self.settings_button.setIcon(settings_icon)

        delete_icon = self.theme_manager.create_icon("msc.trash", IconColors.PRIMARY)
        if delete_icon:
            self.delete_button.setIcon(delete_icon)

on_theme_changed(theme)

Handle theme changes by updating icons

Source code in trace/widgets/control_panel.py
570
571
572
573
574
575
576
def on_theme_changed(self, theme: Theme):
    """Handle theme changes by updating icons"""
    self.update_icons()

    # Change axis label color to match theme
    label_text = self.source.labelText
    self.source.setLabel(label_text, color=self.theme_manager.get_icon_color())

make_curve_widget(plot_curve_item)

Create a CurveItem widget for the given plot curve item and add it to this AxisItem.

Parameters:

Name Type Description Default
plot_curve_item ArchivePlotCurveItem | FormulaCurveItem

The plot curve item to create a CurveItem for.

required

Returns:

Type Description
CurveItem

The created CurveItem widget.

Source code in trace/widgets/control_panel.py
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
def make_curve_widget(self, plot_curve_item: ArchivePlotCurveItem | FormulaCurveItem) -> "CurveItem":
    """Create a CurveItem widget for the given plot curve item and add
    it to this AxisItem.

    Parameters
    ----------
    plot_curve_item : ArchivePlotCurveItem | FormulaCurveItem
        The plot curve item to create a CurveItem for.

    Returns
    -------
    CurveItem
        The created CurveItem widget.
    """
    curve_item = CurveItem(self, plot_curve_item)
    curve_item.curve_deleted.connect(lambda curve: self.handle_curve_deleted(curve))
    curve_item.active_toggle.setCheckState(self.active_toggle.checkState())

    self.layout().addWidget(curve_item)
    self.curves_list_changed.emit()

    if not self._expanded:
        self.toggle_expand()

    return curve_item

add_curve(pv, channel_args=None)

Create a new ArchivePlotCurveItem for the given PV and add it to this AxisItem. Also creates a CurveItem widget for it.

Parameters:

Name Type Description Default
pv str

The process variable name to create the curve for.

required
channel_args dict

The arguments to pass to the ArchivePlotCurveItem constructor, by default None

None

Returns:

Type Description
CurveItem

The created CurveItem widget.

Source code in trace/widgets/control_panel.py
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
def add_curve(self, pv: str, channel_args: dict = None) -> "CurveItem":
    """Create a new ArchivePlotCurveItem for the given PV and add it
    to this AxisItem. Also creates a CurveItem widget for it.

    Parameters
    ----------
    pv : str
        The process variable name to create the curve for.
    channel_args : dict, optional
        The arguments to pass to the ArchivePlotCurveItem constructor,
        by default None

    Returns
    -------
    CurveItem
        The created CurveItem widget.
    """
    palette = self.control_panel.curve_palette
    color = ColorButton.index_color(len(self.plot._curves), palette=palette)
    args = {
        "y_channel": pv,
        "name": pv,
        "color": color,
        "useArchiveData": True,
        "yAxisName": self.source.name,
    }
    if channel_args is not None:
        args.update(channel_args)

    plot_curve_item = self.plot.addYChannel(**args)
    plot_curve_item.stepMode = "right"

    return self.make_curve_widget(plot_curve_item)

add_formula_curve(formula)

Create a new FormulaCurveItem for the given formula and add it to this AxisItem. Also creates a CurveItem widget for it.

Parameters:

Name Type Description Default
formula str

The formula to create the curve for. Must start with "f://".

required

Returns:

Type Description
CurveItem

The created CurveItem widget.

Source code in trace/widgets/control_panel.py
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
def add_formula_curve(self, formula: str) -> "CurveItem":
    """Create a new FormulaCurveItem for the given formula and add it
    to this AxisItem. Also creates a CurveItem widget for it.

    Parameters
    ----------
    formula : str
        The formula to create the curve for. Must start with "f://".

    Returns
    -------
    CurveItem
        The created CurveItem widget.
    """
    var_names = re.findall(r"{(.+?)}", formula)
    var_dict = {}

    for var_name in var_names:
        if var_name not in self.control_panel._curve_dict:
            available_vars = list(self.control_panel._curve_dict.keys())
            raise ValueError(f"{var_name} is an invalid variable name. Available: {available_vars}")
        var_dict[var_name] = self.control_panel._curve_dict[var_name]

    expr_body = formula[4:]
    python_expr, allowed = sanitize_for_validation(expr_body)
    try:
        validate_formula(python_expr, allowed_symbols=allowed)
    except ValueError as e:
        logger.error(f"Invalid formula '{formula}': {e}")
        raise

    color = ColorButton.index_color((len(self.plot._curves)), palette=self.control_panel.curve_palette)
    formula_curve_item = self.plot.addFormulaChannel(
        formula=formula, name=formula, pvs=var_dict, color=color, useArchiveData=True, yAxisName=self.source.name
    )
    formula_curve_item.formula_invalid_signal.connect(self.auto_hide_invalid_formula)

    return self.make_curve_widget(formula_curve_item)

auto_hide_invalid_formula(formula_curve=None)

Automatically hide a formula when it becomes invalid

Source code in trace/widgets/control_panel.py
686
687
688
689
690
691
692
693
694
695
696
697
@Slot()
@Slot(FormulaCurveItem)
def auto_hide_invalid_formula(self, formula_curve: FormulaCurveItem = None) -> None:
    """Automatically hide a formula when it becomes invalid"""
    if formula_curve is None:
        formula_curve = self.sender()

    curve_item = self.find_curve_item_for_curve(formula_curve)
    if curve_item and hasattr(curve_item, "active_toggle"):
        curve_item.active_toggle.setChecked(False)
        if hasattr(curve_item, "show_invalid_icon"):
            curve_item.show_invalid_icon(True)

find_curve_item_for_curve(target_curve)

Find the CurveItem widget that corresponds to a given curve

Source code in trace/widgets/control_panel.py
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
def find_curve_item_for_curve(self, target_curve):
    """Find the CurveItem widget that corresponds to a given curve"""
    for i in range(self.layout().count()):
        widget = self.layout().itemAt(i).widget()
        if hasattr(widget, "source") and widget.source == target_curve:
            return widget

    for i in range(self.control_panel.axis_list.count() - 1):  # -1 for stretch
        axis_item = self.control_panel.axis_list.itemAt(i).widget()
        if hasattr(axis_item, "layout"):
            for j in range(axis_item.layout().count()):
                widget = axis_item.layout().itemAt(j).widget()
                if hasattr(widget, "source") and widget.source == target_curve:
                    return widget

    return None

set_curve_palette(palette_name, apply=True)

Set colors of all curves on this axisItem according to selected palette

Source code in trace/widgets/control_panel.py
812
813
814
815
816
817
818
819
820
821
def set_curve_palette(self, palette_name: str, apply: bool = True):
    """Set colors of all curves on this axisItem according to selected palette"""
    if apply:
        for j in range(self.layout().count()):
            widget = self.layout().itemAt(j).widget()
            if hasattr(widget, "source"):
                curve = widget.source
                color = ColorButton.index_color(j - 1, palette=palette_name)
                curve.color = color
                self.find_curve_item_for_curve(curve).on_color_changed(color)

remove_curve_item(curve_item, delete_curve=False)

Removes the given CurveItem from the AxisItem and plot's axis. This is required for moving a CurveItem to a new AxisItem. Can delete the CurveItem and curve if specified. This will remove it from the plot.

Parameters:

Name Type Description Default
curve_item CurveItem

The CurveItem to be removed from the axis.

required
delete_curve bool

If True, the CurveItem will be deleted and the curve removed from the plot entirely. If False, it will just be unlinked from this axis., by default False.

False
Source code in trace/widgets/control_panel.py
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
def remove_curve_item(self, curve_item: "CurveItem", delete_curve: bool = False) -> None:
    """Removes the given CurveItem from the AxisItem and plot's axis.
    This is required for moving a CurveItem to a new AxisItem. Can
    delete the CurveItem and curve if specified. This will remove it
    from the plot.

    Parameters
    ----------
    curve_item : CurveItem
        The CurveItem to be removed from the axis.
    delete_curve : bool, optional
        If True, the CurveItem will be deleted and the curve removed
        from the plot entirely. If False, it will just be unlinked
        from this axis., by default False.
    """
    curve_item.curve_deleted.disconnect()
    self.layout().removeWidget(curve_item)
    self.plot.plotItem.unlinkDataFromAxis(curve_item.source)

    if delete_curve:
        curve_item.close()
    self.curves_list_changed.emit()

add_curve_item(curve_item)

Add an existing CurveItem to this AxisItem.

Parameters:

Name Type Description Default
curve_item CurveItem

The CurveItem to be added to this axis.

required
Source code in trace/widgets/control_panel.py
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
def add_curve_item(self, curve_item: "CurveItem") -> None:
    """Add an existing CurveItem to this AxisItem.

    Parameters
    ----------
    curve_item : CurveItem
        The CurveItem to be added to this axis.
    """
    # Need to link curve to axis before setting y_axis_name on curve
    self.plot.plotItem.linkDataToAxis(curve_item.source, self.name)
    curve_item.source.y_axis_name = self.name

    curve_item.curve_deleted.connect(lambda curve: self.handle_curve_deleted(curve))
    curve_item.active_toggle.setCheckState(self.active_toggle.checkState())

    if self.layout().indexOf(curve_item) != -1:
        self.layout().removeWidget(curve_item)

    idx = self.layout().indexOf(self.placeholder)
    self.layout().insertWidget(idx, curve_item)

    if not self._expanded:
        self.toggle_expand()
    self.curves_list_changed.emit()

clear_curves()

Clear all curves from this axis item.

Source code in trace/widgets/control_panel.py
899
900
901
902
903
904
def clear_curves(self) -> None:
    """Clear all curves from this axis item."""
    for i in range(self.layout().count() - 1, -1, -1):
        item = self.layout().itemAt(i).widget()
        if isinstance(item, CurveItem):
            self.remove_curve_item(item, delete_curve=True)

CurveItem(axis_item, source)

Bases: QWidget

Widget for managing a single curve on the plot.

This widget provides controls for curve configuration including name, color, visibility, and connection status. It supports drag-and-drop for moving curves between axes and formula editing for formula curves.

Parameters:

Name Type Description Default
axis_item AxisItem

The parent axis item

required
source ArchivePlotCurveItem or FormulaCurveItem

The plot curve item to manage

required
Source code in trace/widgets/control_panel.py
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
def __init__(self, axis_item: AxisItem, source: ArchivePlotCurveItem | FormulaCurveItem):
    """Initialize the curve item widget.

    Parameters
    ----------
    axis_item : AxisItem
        The parent axis item
    source : ArchivePlotCurveItem or FormulaCurveItem
        The plot curve item to manage
    """
    super().__init__()
    self._axis_item = axis_item
    self.source = source
    self.control_panel = axis_item.control_panel

    self.theme_manager = axis_item.theme_manager
    self.theme_manager.theme_changed.connect(lambda _: self.update_icons())

    self.variable_name = self.control_panel.key_gen.send(self.source)
    self.control_panel.curve_dict[self.variable_name] = self.source

    self.setup_layout()

plot property

Get the PlotWidget that this CurveItem belongs to.

axis_item property

Get the AxisItem that this CurveItem belongs to.

move_to_axis_from_unit()

Automatically move curve to axis based on unit

Source code in trace/widgets/control_panel.py
978
979
980
981
982
983
984
985
def move_to_axis_from_unit(self):
    """Automatically move curve to axis based on unit"""
    if not self.is_formula_curve():
        unit = self.source.units
        if unit:
            self.control_panel.move_curve_to_axis(self, unit)
        else:
            self.source.unitSignal.connect(lambda unit: self.control_panel.move_curve_to_axis(self, unit))

setup_layout()

Setup the layout and widgets for the CurveItem.

Source code in trace/widgets/control_panel.py
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
def setup_layout(self):
    """Setup the layout and widgets for the CurveItem."""
    curve_layout = QtWidgets.QHBoxLayout()
    self.setLayout(curve_layout)

    self.handle = DragHandle()
    self.handle.setFlat(True)
    self.handle.setStyleSheet("border: None;")
    self.handle.setCursor(QtGui.QCursor(QtCore.Qt.OpenHandCursor))
    curve_layout.addWidget(self.handle)

    self.active_toggle = ToggleSwitch("Active", color=self.source.color_string)
    self.active_toggle.setCheckState(QtCore.Qt.Checked if self.source.isVisible() else QtCore.Qt.Unchecked)
    self.active_toggle.stateChanged.connect(self.set_active)
    curve_layout.addWidget(self.active_toggle)

    second_layout = QtWidgets.QVBoxLayout()
    curve_layout.addLayout(second_layout)

    pv_settings_layout = QtWidgets.QHBoxLayout()
    second_layout.addLayout(pv_settings_layout)

    self.invalid_action = None
    self.variable_name_label = QtWidgets.QLabel()
    self.variable_name_label.setMinimumWidth(40)
    self.variable_name_label.setAlignment(QtCore.Qt.AlignCenter)
    self.variable_name_label.setText(self.variable_name)
    self.variable_name_label.setToolTip("Variable name of the curve")
    pv_settings_layout.addWidget(self.variable_name_label)

    self.label = QtWidgets.QLineEdit()
    self.setup_line_edit()
    pv_settings_layout.addWidget(self.label)

    self.pv_settings_modal = None
    self.pv_settings_button = QtWidgets.QPushButton()
    self.pv_settings_button.setFlat(True)
    self.pv_settings_button.clicked.connect(self.show_settings_modal)
    pv_settings_layout.addWidget(self.pv_settings_button)

    self.live_connection_status = QtWidgets.QLabel()
    self.live_connection_status.setToolTip("Not connected to live data")
    self.source.live_channel_connection.connect(self.update_live_icon)
    pv_settings_layout.addWidget(self.live_connection_status)

    self.archive_connection_status = QtWidgets.QLabel()
    self.archive_connection_status.setToolTip("Not connected to archive data")
    self.source.archive_channel_connection.connect(self.update_archive_icon)
    pv_settings_layout.addWidget(self.archive_connection_status)

    self.delete_button = QtWidgets.QPushButton()
    self.delete_button.setFlat(True)
    self.delete_button.clicked.connect(self.close)
    pv_settings_layout.addWidget(self.delete_button)

    self.update_icons()

setup_line_edit()

Set up the line edit with appropriate behavior for formula vs regular curves

Source code in trace/widgets/control_panel.py
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
def setup_line_edit(self):
    """Set up the line edit with appropriate behavior for formula vs regular curves"""
    if self.is_formula_curve():
        text = self.source.formula
        placeholder = "Edit formula (f://...)"
        self.label.editingFinished.connect(self.update_formula)
    else:
        text = self.source.name()
        placeholder = "PV Name"
        self.label.editingFinished.connect(self.set_curve_pv)

    self.label.setText(text)
    self.label.setPlaceholderText(placeholder)
    self.label.returnPressed.connect(self.label.clearFocus)

update_icons()

Update all icons based on current theme

Source code in trace/widgets/control_panel.py
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
@Slot()
def update_icons(self):
    """Update all icons based on current theme"""
    handle_icon = self.theme_manager.create_icon("ph.dots-six-vertical", scale_factor=1.5)
    self.handle.setIcon(handle_icon)

    settings_icon = self.theme_manager.create_icon("msc.settings-gear")
    self.pv_settings_button.setIcon(settings_icon)

    delete_icon = self.theme_manager.create_icon("msc.trash")
    self.delete_button.setIcon(delete_icon)

    icon_disconnected = self.theme_manager.create_icon("msc.debug-disconnect")
    self.live_connection_status.setPixmap(icon_disconnected.pixmap(16, 16))
    self.archive_connection_status.setPixmap(icon_disconnected.pixmap(16, 16))

show_invalid_icon(show=True)

Show or hide the invalid formula icon overlaid on the line edit

Source code in trace/widgets/control_panel.py
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
def show_invalid_icon(self, show=True):
    """Show or hide the invalid formula icon overlaid on the line edit"""
    if not self.is_formula_curve():
        return

    if show:
        if self.invalid_action is None:
            icon = self.theme_manager.create_icon("fa6s.triangle-exclamation", IconColors.ERROR)
            self.invalid_action = self.label.addAction(icon, QtWidgets.QLineEdit.TrailingPosition)
            self.invalid_action.setToolTip("Formula is invalid")

        self.label.setStyleSheet(
            """
            QLineEdit {
                border: 2px solid #d32f2f;
                border-radius: 4px;
                padding: 4px;
            }
            """
        )
    else:
        if self.invalid_action is not None:
            self.label.removeAction(self.invalid_action)
            self.invalid_action = None

        self.label.setStyleSheet("")

        if self.label.toolTip() == "Formula is invalid":
            self.label.setToolTip("")

on_color_changed(color)

Handle color change from settings modal

Source code in trace/widgets/control_panel.py
1154
1155
1156
1157
@QtCore.Slot(object)
def on_color_changed(self, color):
    """Handle color change from settings modal"""
    self.update_color_toggle()

update_color_toggle()

Update the color toggle when the curve color changes

Source code in trace/widgets/control_panel.py
1159
1160
1161
1162
1163
def update_color_toggle(self):
    """Update the color toggle when the curve color changes"""
    if hasattr(self, "active_toggle"):
        curve_color = getattr(self.source, "color_string", None)
        self.active_toggle.setColor(curve_color)

is_formula_curve()

Check if this is a formula curve.

Returns:

Type Description
bool

True if this is a formula curve, False otherwise

Source code in trace/widgets/control_panel.py
1175
1176
1177
1178
1179
1180
1181
1182
1183
def is_formula_curve(self) -> bool:
    """Check if this is a formula curve.

    Returns
    -------
    bool
        True if this is a formula curve, False otherwise
    """
    return isinstance(self.source, FormulaCurveItem)

update_formula()

Handle formula updates when user edits the formula text.

Source code in trace/widgets/control_panel.py
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
def update_formula(self) -> None:
    """Handle formula updates when user edits the formula text."""
    if hasattr(self, "_updating_formula") and self._updating_formula:
        return

    self.show_invalid_icon(False)

    new_formula = self.label.text().strip()

    if not new_formula.startswith("f://"):
        QtWidgets.QMessageBox.warning(
            self, "Invalid Formula", "Formula must start with 'f://'.\nExample: f://{PV1}+2"
        )
        if hasattr(self.source, "formula"):
            self.label.setText(self.source.formula)
        return

    current_formula = getattr(self.source, "formula", "") if hasattr(self.source, "formula") else ""
    if new_formula == current_formula:
        return

    self._updating_formula = True

    try:
        var_names = re.findall(r"{(.+?)}", new_formula)

        for var_name in var_names:
            if var_name not in self.control_panel._curve_dict:
                raise ValueError(
                    f"Variable '{var_name}' not found. Available: {list(self.control_panel._curve_dict.keys())}"
                )

        expr_body = new_formula[4:]
        if var_names:
            python_expr, allowed = sanitize_for_validation(expr_body)
            validate_formula(python_expr, allowed_symbols=allowed)
        else:
            validate_formula(expr_body, allowed_symbols=set())

        def delayed_update():
            try:
                self._perform_formula_update(new_formula)
                self.show_invalid_icon(False)
            except ValueError as e:
                QtWidgets.QMessageBox.critical(None, "Formula Update Failed", f"Failed to update formula: {str(e)}")
                if hasattr(self.source, "formula"):
                    self.label.setText(self.source.formula)
                else:
                    self.show_invalid_icon(True)
            finally:
                if hasattr(self, "_updating_formula"):
                    self._updating_formula = False

        QTimer.singleShot(10, delayed_update)

    except Exception as e:
        self._updating_formula = False
        QtWidgets.QMessageBox.critical(self, "Formula Update Failed", f"Failed to update formula: {str(e)}")
        if hasattr(self.source, "formula"):
            self.label.setText(self.source.formula)
        else:
            self.show_invalid_icon(True)