Table Of Contents

Previous topic

How to contribute

Next topic

GUIData reference

This Page

Examples

Basic example

Source code :

import guidata
guidata.qapplication() # not required if a QApplication has already been created

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

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()

Output :

_images/basic_example.png

Assigning values to data items or using these values is very easy :

param.a = 5.34
param.type = "type 3"
print "a*b =", param.a*param.b

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 tempfile, atexit, shutil, datetime, numpy as np

from guidata.dataset.datatypes import DataSet, BeginGroup, EndGroup
from guidata.dataset.dataitems import (FloatItem, IntItem, BoolItem, ChoiceItem,
                             MultipleChoiceItem, ImageChoiceItem, FilesOpenItem,
                             StringItem, TextItem, ColorItem, FileSaveItem,
                             FileOpenItem, DirectoryItem, FloatArrayItem,
                             DateItem, DateTimeItem)


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

Embedding guidata objects in GUI layouts

from guidata.qt.QtGui import QMainWindow, QSplitter
from guidata.qt.QtCore import SIGNAL

from guidata.dataset.datatypes import (DataSet, BeginGroup, EndGroup,
                                       BeginTabGroup, EndTabGroup)
from guidata.dataset.dataitems import (ChoiceItem, FloatItem, StringItem,
                                       DirectoryItem, FileOpenItem)
from guidata.dataset.qtwidgets import DataSetShowGroupBox, DataSetEditGroupBox
from guidata.configtools import get_icon
from guidata.qthelpers import create_action, add_actions, get_std_icon

# Local test import:
from guidata.tests.activable_dataset import ExampleDataSet

class AnotherDataSet(DataSet):
    """
    Example 2
    <b>Simple dataset example</b>
    """
    param0 = ChoiceItem("Choice", ['deazdazk', 'aeazee', '87575757'])
    param1 = FloatItem("Foobar 1", default=0, min=0)
    a_group = BeginGroup("A group")
    param2 = FloatItem("Foobar 2", default=.93)
    param3 = FloatItem("Foobar 3", default=123)
    _a_group = EndGroup("A group")

class ExampleMultiGroupDataSet(DataSet):
    param0 = ChoiceItem("Choice", ['deazdazk', 'aeazee', '87575757'])
    param1 = FloatItem("Foobar 1", default=0, min=0)
    t_group = BeginTabGroup("T group")
    a_group = BeginGroup("A group")
    param2 = FloatItem("Foobar 2", default=.93)
    dir1 = DirectoryItem("Directory 1")
    file1 = FileOpenItem("File 1")
    _a_group = EndGroup("A group")
    b_group = BeginGroup("B group")
    param3 = FloatItem("Foobar 3", default=123)
    _b_group = EndGroup("B group")
    c_group = BeginGroup("C group")
    param4 = FloatItem("Foobar 4", default=250)
    _c_group = EndGroup("C group")
    _t_group = EndTabGroup("T group")
    
class OtherDataSet(DataSet):
    title = StringItem("Title", default="Title")
    icon = ChoiceItem("Icon", (("python.png", "Python"),
                               ("guidata.svg", "guidata"),
                               ("settings.png", "Settings")))
    opacity = FloatItem("Opacity", default=1., min=.1, max=1)

class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.setWindowIcon(get_icon('python.png'))
        self.setWindowTitle("Application example")
        
        # Instantiate dataset-related widgets:
        self.groupbox1 = DataSetShowGroupBox("Activable dataset",
                                             ExampleDataSet, comment='')
        self.groupbox2 = DataSetShowGroupBox("Standard dataset",
                                             AnotherDataSet, comment='')
        self.groupbox3 = DataSetEditGroupBox("Standard dataset",
                                             OtherDataSet, comment='')
        self.groupbox4 = DataSetEditGroupBox("Standard dataset",
                                             ExampleMultiGroupDataSet, comment='')
        self.connect(self.groupbox3, SIGNAL("apply_button_clicked()"),
                     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):
        dataset = self.groupbox3.dataset
        self.setWindowTitle(dataset.title)
        self.setWindowIcon(get_icon(dataset.icon))
        self.setWindowOpacity(dataset.opacity)
        
    def update_groupboxes(self):
        self.groupbox1.dataset.set_readonly() # This is an activable dataset
        self.groupbox1.get()
        self.groupbox2.get()
        self.groupbox4.get()
        
    def edit_dataset1(self):
        self.groupbox1.dataset.set_writeable() # This is an activable dataset
        if self.groupbox1.dataset.edit():
            self.update_groupboxes()
    
    def edit_dataset2(self):
        if self.groupbox2.dataset.edit():
            self.update_groupboxes()

    def edit_dataset4(self):
        if self.groupbox4.dataset.edit():
            self.update_groupboxes()
        
if __name__ == '__main__':
    from guidata.qt.QtGui import QApplication
    import sys
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())
_images/editgroupbox.png

Data item groups and group selection

from guidata.dataset.datatypes import DataSet, BeginGroup, EndGroup, ValueProp
from guidata.dataset.dataitems import BoolItem, FloatItem

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

class GroupSelection(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=.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=.93).set_prop("display", active=prop2)
    _g2 = EndGroup("group 2")

if __name__ == '__main__':
    # Create QApplication
    import guidata
    _app = guidata.qapplication()
    
    prm = GroupSelection()
    prm.edit()
    print(prm)
_images/bool_selector.png

Activable data sets

from guidata.dataset.datatypes import ActivableDataSet
from guidata.dataset.dataitems import BoolItem, FloatItem, ChoiceItem, ColorItem


class ExampleDataSet(ActivableDataSet):
    """
    Example
    <b>Activable dataset example</b>
    """
    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=.93)
    color = ColorItem("Color", default="red")

ExampleDataSet.active_setup()


if __name__ == '__main__':
    # Create QApplication
    import guidata
    _app = guidata.qapplication()
    
    # Editing mode:
    prm = ExampleDataSet()
    prm.set_writeable()
    prm.edit()
    
    # Showing mode:
    prm.set_readonly()
    prm.view()
_images/activable_dataset.png

Data set groups

from guidata.tests.all_features import TestParameters
from guidata.dataset.datatypes import DataSetGroup

if __name__ == "__main__":
    # Create QApplication
    import guidata
    _app = guidata.qapplication()

    e1 = TestParameters("DataSet #1")
    e2 = TestParameters("DataSet #2")
    g = DataSetGroup( [e1, e2], title='Parameters group' )
    g.edit()
    print(e1)
    g.edit()
_images/datasetgroup.png