编辑guidata选项

2024-04-30 05:54:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在运行时修改guidata.dataset.dataitems.ChoiceItem显示的选项。在

例如:

from guidata.dataset.datatypes import DataSet
from guidata.dataset.dataitems import ChoiceItem

class Example(DataSet):
    choiceBox = ChoiceItem("Example", [(0,'First'),(1,'Second'),(2,'Third')])

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

    win = Example()
    magic_function_to_change_choices(win, [(0,'A'), (1,'B'), (2,'C')])
    win.edit()

Tags: fromimportexample选项windatasetclassfirst
1条回答
网友
1楼 · 发布于 2024-04-30 05:54:34

已编辑

我想出了一个我更喜欢的方法。这将创建一个可以在运行时设置的变量类。在

from guidata.dataset.datatypes import DataSet
from guidata.dataset.dataitems import ChoiceItem, TextItem

class ChoicesVariable(object):
    def __init__(self):
        self.choices = [(0,'First',None),(1,'Second',None),(2,'Third',None)]
    def set(self, choices):
        normalized = []
        for idx, c in enumerate(choices):
            normalized.append(self._normalize_choice(idx, c))
        self.choices = normalized
    def __call__(self, *args):
        return self.choices
    def _normalize_choice(self, idx, choice_tuple):
        img = None
        if isinstance(choice_tuple, tuple):
            if len(choice_tuple) == 2:
                key, value = choice_tuple
            else:
                key, value, img = choice_tuple
        else:
            key = idx
            value = choice_tuple
        if isinstance(value, str):
            value = str(value)        
        return (key, value, img)
choices = ChoicesVariable()



class Example(DataSet):
    choiceBox = ChoiceItem("Example", choices)
    otherChoiceBox = ChoiceItem("Example2", [(0,'DontTouch'),(1,'Second'),(2,'Third')])
    text = TextItem("Example3")

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

    newChoices = [(0,'Aaa'),(1,'Bbb'),(2,'Ccc')]
    choices.set(newChoices)
    #Example._items[0].set_prop('data', choices=newChoices)
    win = Example()
    win.edit()
    newChoices = [(0,'Alpha',None),(1,'Beta',None),(2,'Gamma',None)]
    choices.set(newChoices)
    win.edit()

相关问题 更多 >