fyne的VBox布局
最常用的布局是layout.BoxLayout,它有两种变体,水平和垂直。box布局将所有元素排列在单行或单列中,并带有可选的空格以帮助对齐。
一步一步实现一个如下界面布局,这个界面可以使用VBox布局来实现。
代码1
package main
import (
"fyne.io/fyne/v2"
"fyne.io/fyne/v2/app"
"fyne.io/fyne/v2/container"
"fyne.io/fyne/v2/widget"
)
func main() {
a := app.New()
w := a.NewWindow("Newlock")
input := widget.NewEntry()
input.SetPlaceHolder("Enter Password Length")
c := container.NewVBox(input)
w.SetContent(c)
w.Resize(fyne.NewSize(400, 300))
w.ShowAndRun()
}
效果如下:
代码2
package main
import (
"fyne.io/fyne/v2"
"fyne.io/fyne/v2/app"
"fyne.io/fyne/v2/widget"
)
func main() {
a := app.New()
w := a.NewWindow("Newlock")
input := widget.NewEntry()
input.SetPlaceHolder("Enter Password Length")
w.SetContent(input)
w.Resize(fyne.NewSize(400, 300))
w.ShowAndRun()
}
效果如下:
这2份代码的区别是w.SetContent(),第一个被容器包裹,第二个未被容器包裹。
分析NewVBox()
分析container.New()和container.NewWithoutLayout():
// Package container provides containers that are used to lay out and organise applications.
package container
import (
"fyne.io/fyne/v2"
)
// New returns a new Container instance holding the specified CanvasObjects which will be laid out according to the specified Layout.
//
// Since: 2.0
func New(layout fyne.Layout, objects ...fyne.CanvasObject) *fyne.Container {
return &fyne.Container{Layout: layout, Objects: objects}
}
// NewWithoutLayout returns a new Container instance holding the specified CanvasObjects that are manually arranged.
//
// Since: 2.0
func NewWithoutLayout(objects ...fyne.CanvasObject) *fyne.Container {
return &fyne.Container{Objects: objects}
}
New()函数的第一个参数是layout布局参数,其它参数是canvas对象。
NewWithoutLayout()函数没有layout布局参数。
fyne.Container结构体如下:
// Container is a CanvasObject that contains a collection of child objects.
// The layout of the children is set by the specified Layout.
type Container struct {
size Size // The current size of the Container
position Position // The current position of the Container
Hidden bool // Is this Container hidden
Layout Layout // The Layout algorithm for arranging child CanvasObjects
lock sync.Mutex
Objects []CanvasObject // The set of CanvasObjects this container holds
}
这个结构体包含一个Layout布局和一个CanvasObject数组。
container.NewVBox()源码:
// NewVBox creates a new container with the specified objects and using the VBox layout.
// The objects will be stacked in the container from top to bottom and always displayed
// at their vertical MinSize. Use a different layout if the objects are intended
// to be larger then their vertical MinSize.
//
// Since: 1.4
func NewVBox(objects ...fyne.CanvasObject) *fyne.Container {
return New(layout.NewVBoxLayout(), objects...)
}
container.NewVBox(input)
//可以替换为
container.New(layout.NewVBoxLayout(), input)
layout.NewSpacer()返回一个可以填充垂直和水平空间的间隔对象。这主要用于box布局。
canvas.NewText()和widget.NewLabel()区别
canvas.NewText()
: 在fyne
库中,canvas.Text
是一个低级的文本绘制对象,它允许你更精细地控制文本的布局、样式和渲染。widget.NewLabel()
: 这与更高级的GUI小部件(widgets)相关。Label
是一个预制的、可重用的界面元素,它封装了文本的显示,并可能还包含一些额外的功能,如响应鼠标点击或键盘输入。