Golang Gtk+3教程:GtkBuilder使用XML构建UI

在这节我将介绍GtkBuilder,其使我们可以从一个描述界面的xml文件构建UI。而这个文件我们可以使用Glade生成,这会极大的方便我们编辑用户界面。这节我们会使用到这么一个XML文件,名字为Builder.ui(可以在本文后面看到,请创建并放在项目下)。习惯上,我们使用.ui作为扩展名。

示例:

package main

import (
	"github.com/gotk3/gotk3/glib"
	"github.com/gotk3/gotk3/gtk"
	"log"
	"os"
)

func main() {
	const appId = "com.nayoso.example"

	app, _ := gtk.ApplicationNew(appId, glib.APPLICATION_FLAGS_NONE)
	app.Connect("activate", func() {
		onActivate(app)
	})
	app.Run(os.Args)
}
//-- 在开始我们还是使用我们熟悉的代码

func onActivate(application *gtk.Application) {
	if builder, err := gtk.BuilderNewFromFile("builder.ui"); err != nil {	//从文件中创建Builder
		log.Fatal(err)
	} else if winObj, err := builder.GetObject("window"); err != nil {	//从文件中读取window对象,其实际上是Gobject
		log.Fatal(err)
	} else {
		window := winObj.(*gtk.Window)	//由于winObj是Gobject,所以我们使用类型断言得到Gtk.Window对象
        application.AddWindow(window)	//记得将window加入我们的application中
        
		window.ShowAll()
	}
}

Builder.ui的内容:

<interface>
    <object id="window" class="GtkWindow">
        <property name="visible">True</property>
        <property name="title">Grid</property>
        <property name="border-width">10</property>
        <child>
            <object id="grid" class="GtkGrid">
                <property name="visible">True</property>
                <child>
                    <object id="button1" class="GtkButton">
                        <property name="visible">True</property>
                        <property name="label">Button 1</property>
                    </object>
                    <packing>
                        <property name="left-attach">0</property>
                        <property name="top-attach">0</property>
                    </packing>
                </child>
                <child>
                    <object id="button2" class="GtkButton">
                        <property name="visible">True</property>
                        <property name="label">Button 2</property>
                    </object>
                    <packing>
                        <property name="left-attach">1</property>
                        <property name="top-attach">0</property>
                    </packing>
                </child>
                <child>
                    <object id="quit" class="GtkButton">
                        <property name="visible">True</property>
                        <property name="label">Quit</property>
                    </object>
                    <packing>
                        <property name="left-attach">0</property>
                        <property name="top-attach">1</property>
                        <property name="width">2</property>
                    </packing>
                </child>
            </object>
            <packing>
            </packing>
        </child>
    </object>
</interface>

知识共享许可协议
本作品采用知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议进行许可。转载请注明出处!

原文地址:https://www.cnblogs.com/xiyu714/p/9912203.html