Examples

Basic example

Source code :

# -*- coding: utf-8 -*-

import guidata
import guidata.dataset.dataitems as di
import guidata.dataset.datatypes as dt

# Note: the following line is not required if a QApplication has already been created
_app = guidata.qapplication()


class Processing(dt.DataSet):
    """Example"""

    a = di.FloatItem("Parameter #1", default=2.3)
    b = di.IntItem("Parameter #2", min=0, max=10, default=5)
    type = di.ChoiceItem("Processing algorithm", ("type 1", "type 2", "type 3"))


param = Processing()
param.edit()
print(param)  # Showing param contents
param.b = 4  # Modifying item value
param.view()

# Alternative way for creating a DataSet instance:
param = Processing.create(a=7.323, b=4)
print(param)

Other examples

A lot of examples are available in the guidata test module

from guidata import tests
tests.run()

The two lines above execute the guidata test launcher :

_images/__init__.png

All guidata items demo


import atexit
import datetime
import shutil
import tempfile

import numpy as np

import guidata.dataset.dataitems as gdi
import guidata.dataset.datatypes as gdt
from guidata.env import execenv
from guidata.qthelpers import qt_app_context

# Creating temporary files and registering cleanup functions
TEMPDIR = tempfile.mkdtemp(prefix="test_")
atexit.register(shutil.rmtree, TEMPDIR)
FILE_ETA = tempfile.NamedTemporaryFile(suffix=".eta", dir=TEMPDIR)
atexit.register(FILE_ETA.close)
FILE_CSV = tempfile.NamedTemporaryFile(suffix=".csv", dir=TEMPDIR)
atexit.register(FILE_CSV.close)


class Parameters(gdt.DataSet):
    """
    DataSet test
    The following text is the DataSet 'comment': <br>Plain text or
    <b>rich text<sup>2</sup></b> are both supported,
    as well as special characters (α, β, γ, δ, ...)
    """

    dir = gdi.DirectoryItem("Directory", TEMPDIR)
    fname = gdi.FileOpenItem("Open file", ("csv", "eta"), FILE_CSV.name)
    fnames = gdi.FilesOpenItem("Open files", "csv", FILE_CSV.name)
    fname_s = gdi.FileSaveItem("Save file", "eta", FILE_ETA.name)
    string = gdi.StringItem("String")
    text = gdi.TextItem("Text")
    float_slider = gdi.FloatItem(
        "Float (with slider)", default=0.5, min=0, max=1, step=0.01, slider=True
    )
    integer = gdi.IntItem("Integer", default=5, min=3, max=16, slider=True).set_pos(
        col=1
    )
    dtime = gdi.DateTimeItem("Date/time", default=datetime.datetime(2010, 10, 10))
    date = gdi.DateItem("Date", default=datetime.date(2010, 10, 10)).set_pos(col=1)
    bool1 = gdi.BoolItem("Boolean option without label")
    bool2 = gdi.BoolItem("Boolean option with label", "Label")
    _bg = gdt.BeginGroup("A sub group")
    color = gdi.ColorItem("Color", default="red")
    choice = gdi.ChoiceItem(
        "Single choice 1",
        [("16", "first choice"), ("32", "second choice"), ("64", "third choice")],
    )
    mchoice2 = gdi.ImageChoiceItem(
        "Single choice 2",
        [
            ("rect", "first choice", "gif.png"),
            ("ell", "second choice", "txt.png"),
            ("qcq", "third choice", "file.png"),
        ],
    )
    _eg = gdt.EndGroup("A sub group")
    floatarray = gdi.FloatArrayItem(
        "Float array", default=np.ones((50, 5), float), format=" %.2e "
    ).set_pos(col=1)
    mchoice3 = gdi.MultipleChoiceItem(
        "MC type 1", [str(i) for i in range(12)]
    ).horizontal(4)
    mchoice1 = (
        gdi.MultipleChoiceItem(
            "MC type 2", ["first choice", "second choice", "third choice"]
        )
        .vertical(1)
        .set_pos(col=1)
    )


def test_all_items():
    """Test all DataItem objects"""
    with qt_app_context():
        e = Parameters()

        e.floatarray[:, 0] = np.linspace(-5, 5, 50)
        execenv.print(e)
        if e.edit():
            execenv.print(e)
        e.view()
        execenv.print("OK")


if __name__ == "__main__":
    test_all_items()
_images/all_items.png

Embedding guidata objects in GUI layouts


from qtpy.QtWidgets import QMainWindow, QSplitter

from guidata.configtools import get_icon
from guidata.dataset import dataitems as gdi
from guidata.dataset import datatypes as gdt
from guidata.dataset.qtwidgets import DataSetEditGroupBox, DataSetShowGroupBox
from guidata.env import execenv
from guidata.qthelpers import (
    add_actions,
    create_action,
    get_std_icon,
    qt_app_context,
    win32_fix_title_bar_background,
)

# Local test import:
from guidata.tests.test_activable_dataset import Parameters


class AnotherDataSet(gdt.DataSet):
    """
    Example 2
    <b>Simple dataset example</b>
    """

    param0 = gdi.ChoiceItem("Choice", ["deazdazk", "aeazee", "87575757"])
    param1 = gdi.FloatItem("Foobar 1", default=0, min=0)
    a_group = gdt.BeginGroup("A group")
    param2 = gdi.FloatItem("Foobar 2", default=0.93)
    param3 = gdi.FloatItem("Foobar 3", default=123)
    _a_group = gdt.EndGroup("A group")


class ExampleMultiGroupDataSet(gdt.DataSet):
    """Example DS with multiple groups"""

    param0 = gdi.ChoiceItem("Choice", ["deazdazk", "aeazee", "87575757"])
    param1 = gdi.FloatItem("Foobar 1", default=0, min=0)
    t_group = gdt.BeginTabGroup("T group")
    a_group = gdt.BeginGroup("A group")
    param2 = gdi.FloatItem("Foobar 2", default=0.93)
    dir1 = gdi.DirectoryItem("Directory 1")
    file1 = gdi.FileOpenItem("File 1")
    _a_group = gdt.EndGroup("A group")
    b_group = gdt.BeginGroup("B group")
    param3 = gdi.FloatItem("Foobar 3", default=123)
    param4 = gdi.BoolItem("Boolean")
    _b_group = gdt.EndGroup("B group")
    c_group = gdt.BeginGroup("C group")
    param5 = gdi.FloatItem("Foobar 4", default=250)
    param6 = gdi.DateItem("Date").set_prop("display", format="dd.MM.yyyy")
    param7 = gdi.ColorItem("Color")
    _c_group = gdt.EndGroup("C group")
    _t_group = gdt.EndTabGroup("T group")


class OtherDataSet(gdt.DataSet):
    """Another example dataset"""

    title = gdi.StringItem("Title", default="Title")
    icon = gdi.ChoiceItem(
        "Icon",
        (
            ("python.png", "Python"),
            ("guidata.svg", "guidata"),
            ("settings.png", "Settings"),
        ),
    )
    opacity = gdi.FloatItem("Opacity", default=1.0, min=0.1, max=1)


class MainWindow(QMainWindow):
    """Main window"""

    def __init__(self):
        QMainWindow.__init__(self)
        win32_fix_title_bar_background(self)
        self.setWindowIcon(get_icon("python.png"))
        self.setWindowTitle("Application example")

        # Instantiate dataset-related widgets:
        self.groupbox1 = DataSetShowGroupBox(
            "Activable dataset", Parameters, comment=""
        )
        self.groupbox2 = DataSetShowGroupBox(
            "Standard dataset", AnotherDataSet, comment=""
        )
        self.groupbox3 = DataSetEditGroupBox(
            "Standard dataset", OtherDataSet, comment=""
        )
        self.groupbox4 = DataSetEditGroupBox(
            "Standard dataset", ExampleMultiGroupDataSet, comment=""
        )
        self.groupbox3.SIG_APPLY_BUTTON_CLICKED.connect(self.update_window)
        self.update_groupboxes()

        splitter = QSplitter(self)
        splitter.addWidget(self.groupbox1)
        splitter.addWidget(self.groupbox2)
        splitter.addWidget(self.groupbox3)
        splitter.addWidget(self.groupbox4)
        self.setCentralWidget(splitter)
        self.setContentsMargins(10, 5, 10, 5)

        # File menu
        file_menu = self.menuBar().addMenu("File")
        quit_action = create_action(
            self,
            "Quit",
            shortcut="Ctrl+Q",
            icon=get_std_icon("DialogCloseButton"),
            tip="Quit application",
            triggered=self.close,
        )
        add_actions(file_menu, (quit_action,))

        # Edit menu
        edit_menu = self.menuBar().addMenu("Edit")
        editparam1_action = create_action(
            self, "Edit dataset 1", triggered=self.edit_dataset1
        )
        editparam2_action = create_action(
            self, "Edit dataset 2", triggered=self.edit_dataset2
        )
        editparam4_action = create_action(
            self, "Edit dataset 4", triggered=self.edit_dataset4
        )
        add_actions(
            edit_menu, (editparam1_action, editparam2_action, editparam4_action)
        )

    def update_window(self):
        """Update window"""
        dataset = self.groupbox3.dataset
        self.setWindowTitle(dataset.title)
        self.setWindowIcon(get_icon(dataset.icon))
        self.setWindowOpacity(dataset.opacity)

    def update_groupboxes(self):
        """Update groupboxes"""
        self.groupbox1.dataset.set_readonly()  # This is an activable dataset
        self.groupbox1.get()
        self.groupbox2.get()
        self.groupbox4.get()

    def edit_dataset1(self):
        """Edit dataset 1"""
        self.groupbox1.dataset.set_writeable()  # This is an activable dataset
        if self.groupbox1.dataset.edit(self):
            self.update_groupboxes()

    def edit_dataset2(self):
        """Edit dataset 2"""
        if self.groupbox2.dataset.edit(self):
            self.update_groupboxes()

    def edit_dataset4(self):
        """Edit dataset 4"""
        if self.groupbox4.dataset.edit(self):
            self.update_groupboxes()


def test_editgroupbox():
    """Test editgroupbox"""
    with qt_app_context(exec_loop=True):
        window = MainWindow()
        window.show()
        execenv.print("OK")


if __name__ == "__main__":
    test_editgroupbox()
_images/editgroupbox.png

Data item groups and group selection


from guidata.dataset.dataitems import BoolItem, FloatItem
from guidata.dataset.datatypes import BeginGroup, DataSet, EndGroup, ValueProp
from guidata.env import execenv
from guidata.qthelpers import qt_app_context

prop1 = ValueProp(False)
prop2 = ValueProp(False)


class Parameters(DataSet):
    """
    Group selection test
    <b>Group selection example:</b>
    """

    g1 = BeginGroup("group 1")
    enable1 = BoolItem(
        "Enable parameter set #1",
        help="If disabled, the following parameters will be ignored",
        default=False,
    ).set_prop("display", store=prop1)
    param1_1 = FloatItem("Param 1.1", default=0, min=0).set_prop(
        "display", active=prop1
    )
    param1_2 = FloatItem("Param 1.2", default=0.93).set_prop("display", active=prop1)
    _g1 = EndGroup("group 1")
    g2 = BeginGroup("group 2")
    enable2 = BoolItem(
        "Enable parameter set #2",
        help="If disabled, the following parameters will be ignored",
        default=True,
    ).set_prop("display", store=prop2)
    param2_1 = FloatItem("Param 2.1", default=0, min=0).set_prop(
        "display", active=prop2
    )
    param2_2 = FloatItem("Param 2.2", default=0.93).set_prop("display", active=prop2)
    _g2 = EndGroup("group 2")


def test_bool_selector():
    """Test bool selector"""
    with qt_app_context():
        prm = Parameters()
        prm.edit()
        execenv.print(prm)
        execenv.print("OK")


if __name__ == "__main__":
    test_bool_selector()
_images/bool_selector.png

Activable data sets



class Parameters(ActivableDataSet):
    """
    Example
    <b>Activable dataset example</b>
    """

    def __init__(self, title=None, comment=None, icon=""):
        ActivableDataSet.__init__(self, title, comment, icon)

    enable = BoolItem(
        "Enable parameter set",
        help="If disabled, the following parameters will be ignored",
        default=False,
    )
    param0 = ChoiceItem("Param 0", ["choice #1", "choice #2", "choice #3"])
    param1 = FloatItem("Param 1", default=0, min=0)
    param2 = FloatItem("Param 2", default=0.93)
    color = ColorItem("Color", default="red")


Parameters.active_setup()


def test_activable_dataset():
    """Test activable dataset"""
    with qt_app_context():
        prm = Parameters()
        prm.set_writeable()
        prm.edit()
        prm.set_readonly()
        prm.view()
        execenv.print("OK")


if __name__ == "__main__":
    test_activable_dataset()
_images/activable_dataset.png

Data set groups


from guidata.dataset.datatypes import DataSetGroup
from guidata.env import execenv
from guidata.qthelpers import qt_app_context
from guidata.tests.test_all_features import Parameters


def test_dataset_group():
    """Test DataSetGroup"""
    with qt_app_context():
        e1 = Parameters("DataSet #1")
        e2 = Parameters("DataSet #2")
        g = DataSetGroup([e1, e2], title="Parameters group")
        g.edit()
        execenv.print(e1)
        g.edit()
        execenv.print("OK")


if __name__ == "__main__":
    test_dataset_group()
_images/datasetgroup.png