登录
首页 >  Golang >  Go问答

使用基于 OOP 的 fyne 小组件

来源:stackoverflow

时间:2024-02-26 15:30:27 263浏览 收藏

在Golang实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天golang学习网就整理分享《使用基于 OOP 的 fyne 小组件》,聊聊,希望可以帮助到正在努力赚钱的你。

问题内容

我想将一些标准小部件合并到一个自定义小部件中。如果将所有小部件字段放入一个容器中,我就可以做到这一点,如下所示:

package main

import (
    "fmt"

    "fyne.io/fyne"
    "fyne.io/fyne/app"
    "fyne.io/fyne/layout"
    "fyne.io/fyne/widget"
)

type MyWidget struct {
    widget.BaseWidget

    Cont      *fyne.Container
    text      *widget.Label
    statusBar *widget.Label
    b1        *widget.Button
    b2        *widget.Button

    count uint
}

func (t *MyWidget) Init() {
    t.b1 = widget.NewButton("1", func() {
        t.text.SetText("1")
        t.count++
        t.statusBar.SetText(fmt.Sprint(t.count))
    })
    t.b2 = widget.NewButton("2", func() { t.text.SetText("2") })
    t.statusBar = widget.NewLabel("status")
    bottom := fyne.NewContainerWithLayout(layout.NewCenterLayout(), t.statusBar)
    t.text = widget.NewLabelWithStyle("0", fyne.TextAlignTrailing, fyne.TextStyle{Bold: true})
    t.Cont = fyne.NewContainerWithLayout(layout.NewBorderLayout(nil, bottom, nil, nil),
        bottom, fyne.NewContainerWithLayout(
            layout.NewGridLayoutWithRows(4),
            fyne.NewContainerWithLayout(layout.NewCenterLayout(), t.text),
            layout.NewSpacer(),
            fyne.NewContainerWithLayout(layout.NewGridLayout(2), t.b1, t.b2),
            layout.NewSpacer(),
        ))
}

func Load() *MyWidget {
    obj := &MyWidget{BaseWidget: widget.BaseWidget{}}
    obj.Init()
    return obj
}

func main() {
    f := app.New()
    w := f.NewWindow("")
    obj := Load()
    w.SetContent(obj.Cont)
    w.ShowAndRun()
}

我曾经使用 gui 工具包,其中顶部小部件有机会设置用于容纳子小部件的容器。是否可以在不导出内部容器的情况下使用 fyne 获得解决方案?


解决方案


我建议您考虑使用容器。 (即“fyne.NewContainerWithLayout(myLayout, widgets...)”。

Fyne 中的小部件和容器是不同的。 Widget是对逻辑的封装,通过渲染器来显示,Container用于对多个Widget进行分组。 有一些小部件可以弥补这一差距,例如 widget.Box 和 widget.Group,但它们通常会公开容器,或重新导出容器方法。

通常,您不会创建一个小部件树,而是创建一个在循环中包含小部件的容器树。

终于介绍完啦!小伙伴们,这篇关于《使用基于 OOP 的 fyne 小组件》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>