Hover¶
Changing when the mouse is on the widget.
To apply hover behavior, you must create a new class that is inherited from the
widget to which you apply the behavior and from the HoverBehavior
class.
In KV file:
<MenuItem@MDLabel+HoverBehavior>
In python file:
class MenuItem(MDLabel, HoverBehavior):
'''Custom menu item implementing hover behavior.'''
After creating a class, you must define two methods for it:
HoverBehavior.on_enter
and HoverBehavior.on_leave
, which will be automatically called
when the mouse cursor is over the widget and when the mouse cursor goes beyond
the widget.
from kivy.factory import Factory
from kivy.lang import Builder
from kivymd.app import MDApp
from kivymd.uix.label import MDLabel
from kivymd.uix.behaviors import HoverBehavior
Builder.load_string('''
#:import MDDropdownMenu kivymd.uix.menu.MDDropdownMenu
<HoverBehaviorExample@Screen>
MDRaisedButton:
text: "Open menu"
pos_hint: {'center_x': .5, 'center_y': .5}
on_release: MDDropdownMenu(items=app.menu_items, width_mult=4).open(self)
''')
class MenuItem(MDLabel, HoverBehavior):
'''Custom menu item implementing hover behavior.'''
def on_enter(self, *args):
'''The method will be called when the mouse cursor
is within the borders of the current widget.'''
self.text_color = [1, 1, 1, 1]
def on_leave(self, *args):
'''The method will be called when the mouse cursor goes beyond
the borders of the current widget.'''
self.text_color = [0, 0, 0, 1]
class Test(MDApp):
menu_items = []
def build(self):
self.menu_items = [
{
"viewclass": "MenuItem",
"text": "Example item %d" % i,
"theme_text_color": "Custom",
"text_color": [0, 0, 0, 1],
"halign": "center",
}
for i in range(5)
]
return Factory.HoverBehaviorExample()
Test().run()
API - kivymd.uix.behaviors.hover_behavior
¶
-
class
kivymd.uix.behaviors.hover_behavior.
HoverBehavior
(**kwargs)¶ Bases:
object
- Events
on_enter
Fired when mouse enter the bbox of the widget.
on_leave
Fired when the mouse exit the widget.
-
hovered
¶ True, if the mouse cursor is within the borders of the widget.
hovered
is anBooleanProperty
and defaults to False.
-
border_point
¶ Contains the last relevant point received by the Hoverable. This can be used in
on_enter
oron_leave
in order to know where was dispatched the event.border_point
is anObjectProperty
and defaults to None.
-
on_mouse_pos
(self, *args)¶
-
on_enter
(self)¶ Fired when mouse enter the bbox of the widget.
-
on_leave
(self)¶ Fired when the mouse exit the widget.