能否在Flet中为AppBar创建自定义类?现有实现失效求解答
Flet中自定义AppBar类的正确实现方式
你当前的实现不可行,原因是page.appbar要求赋值的是ft.AppBar类型的实例,而你写的Header继承自ft.UserControl,本质是用户控件,并非AppBar本身,所以无法被页面识别为导航栏。
正确的做法是让自定义类直接继承ft.AppBar,而不是UserControl,代码示例如下:
自定义Header类:
class Header(ft.AppBar): def __init__(self): super().__init__( leading=ft.Icon(ft.icons.PALETTE), leading_width=40, title=ft.Text("AppBar Example"), )
main函数中的使用:
def main(page: ft.Page): header = Header() page.appbar = header page.update() if __name__ == "__main__": ft.app(target=main)
如果后续需要给这个自定义Header添加额外功能,比如自定义方法、动态修改属性等,直接在Header类中扩展即可,它完全兼容page.appbar的使用要求。
内容的提问来源于stack exchange,提问作者united news
相关产品推荐
相关产品推荐

