Creating a custom widget - Part 2

Note that this tutorial builds on part 1

Welcome to part 2 of creating a custom widget in uxpython.

In this tutorial we will learn:

  • Setting and Using Styles
  • Observing attributes
  • Handling Events
  • Using behaviors

Styles

Styles in uxpython is similar to css you might be used to in web development. You use styles to control both appearance and some layout options.

So lets start by modifying our previous widget's constructor to:

You set styles by using the "style" object available in every widget. The properties try to use the equivelent css names. In our example we set the background to white(#FFFFFF) and the text color to burnt orange(#BF711D) while aligning text to center.

You can also use CSS style declarations like this:

Now to actually use the styles we have to change our rendering method to this:

Now we just use the styles in our render method. The showText method is a helper to display text according to the styles we have set. It uses the text property I will explain in the next section.

Observing properties

Sometimes you have important properties that you want to be notified if they change and if they change the user interface should update. In uxpython we have a mechanism to do this. Its called the Observe method and allows an event to be fired when an attribute changes plus it marks the widget as needing rendering.

In your constructor put the following:

It's not necessary to put Observe in init but it is recommended. Now you need to implement the event handler you specified

Events

In the previous section I lightly touched upon event handling. Event handlers are specified by using addEvent with the type as first parameter eg. "click", 2nd parameter the function callback, 3rd the optional bool if it should be run asynchronously (not block UI updates) and 4th parameters that should be passed to the function callback

Put the following in init:

and the associated functions:

Behaviors

Behaviors are classes that add functionality to your widget mainly through using events. Custom behaviours will be covered in a future tutorial.

We will add a hover behaviour to our widget. The hover behaviour will alter the state of our widget. The widget state is a property that describes the state a widget is in. eg: "click","normal","hover"

Styles are affected by the widget state. You can set a specific style for a state by starting your declaration with the state followed by a ":". eg: self.style.background = ":hover #F5F5F5"

Add the following to the constructor:

As you can see the behaviour automatically toggles the state, and the state switched between the styles you have selected.

Conclusion

That's all for now. In part 3 we look at child widgets and layout managers.

Code for this tutorial

[widget2.py]

and the window runner: [runner.py]

Made in South Africa
  blog sitemap contact us