To build our first qt application with Go, let's make another Hello World application. As with previous examples, we'll make use of a simple vertical box layout within a single application window. The following code should be sufficient to load your first application:
package main
import (
"os"
"github.com/therecipe/qt/widgets"
)
func main() {
app := widgets.NewQApplication(len(os.Args), os.Args)
window := widgets.NewQMainWindow(nil, 0)
window.SetWindowTitle("Hello World")
widget := widgets.NewQWidget(window, 0)
widget.SetLayout(widgets.NewQVBoxLayout())
window.SetCentralWidget(widget)
label := widgets.NewQLabel2("Hello World!", window, 0)
widget.Layout().AddWidget(label)
button := widgets.NewQPushButton2("Quit", window)
button.ConnectClicked(func(bool) {
app.QuitDefault()
})
widget.Layout().AddWidget(button)
window.Show()
widgets.QApplication_Exec()
}
Let's note a few details from this code snippet. You'll see that each of the widget constructor functions takes (typically) two parameters, each is the parent widget and a flags parameter. Additional types passed in will usually be added before these values with a note in the function name that there are additional parameters. For example, widgets.NewQLabel2(title, parent, flags) is equivalent to widgets.NewQLabel(parent, flags).SetTitle(title). Additionally, you'll see that the layout is applied to a new widgets.QWidget through SetLayout(layout), and that's set to the window content through window.SetCentralWidget(widget).
To load the display and run the application, we call window.Show() and then widgets.QApplication_Exec(). This file is built in the usual way with go build hello.go:
The file built is quite large due to the size of the Qt framework. This will be reduced significantly when packaging for a specific distribution. This topic will be covered in depth in Chapter 14, Distributing your Application.