CreateUIUsingXML
(:title Create UI using XML):
| Writing your own widgets | Widgets |
In this document
To create UI using XML, you need to use the XMLWidget. It's preferable to use a class for embedding the xml + event handler. Here is an example of XML :
class MainUI(MTBoxLayout:)
xml = '''
<MTBoxLayout>
<MTButton label="1" id='"btn1"'/>
<MTButton label="2" id='"btn2"'/>
<MTButton label="3" id='"btn3"'/>
</MTBoxLayout>
'''
def __init__(self, **kwargs):
super(MainUI, self).__init__(**kwargs)
xml = XMLWidget(xml=MainUI.xml)
xml.autoconnect(self)
self.add_widget(xml.root)
def on_btn2_press(self, *largs):
print 'my button2 is pressed'
xml = '''
<MTBoxLayout>
<MTButton label="1" id='"btn1"'/>
<MTButton label="2" id='"btn2"'/>
<MTButton label="3" id='"btn3"'/>
</MTBoxLayout>
'''
def __init__(self, **kwargs):
super(MainUI, self).__init__(**kwargs)
xml = XMLWidget(xml=MainUI.xml)
xml.autoconnect(self)
self.add_widget(xml.root)
def on_btn2_press(self, *largs):
print 'my button2 is pressed'
Things are very simple:
- You create an instance of XMLWidget and pass your xml definition
- You try to connect event from button to the class
- Last, you're adding the root of xml to our widget.
Event auto binding
The method autoconnect() will search for handler automaticly in the instance passed as the first argument.
In the example, the button with the id = "btn2" is found. It will search for a method named : on_<widgetid>_<eventname>.
So you can declare method like on_btn1_release, on_btn3_touch_down... and put action on this handler.
Warning about XML
In XMLWidget, the value of each attribute actually use eval() to understand the content. Be careful to not pass user data, otherwise, you'll introduce a security issue !
