简介 环境准备
  1. macOS Catalina 10.15.7
  2. go v1.14.4
  3. qt v5.13.0
  4. therecipe/qt
  5. Xcode v12.0.1 / xcode-select --install
Xcode v12.0.1 / xcode-select --install
GO安装

golang安装相对简单,这里要注意设置GOBIN目录

本文设置的GOBIN目录如下
export GOBIN=/Users/tickstep/Applications/go/bin

需要增加到环境变量
export PATH=$GOBIN:$PATH
QT安装

目前therecipe/qt对应的QT的版本是 5.13.0,如果不是这个版本会编译报错。
下载

https://download.qt.io/official_releases/qt/5.13/5.13.0/qt-opensource-mac-x64-5.13.0.dmg

选择以下组件,等待安装完毕即可


Qt组件选择

记录下安装的目录,本文安装的目录是

/Users/tickstep/Applications/Qt5.13.0
therecipe/qt 安装

官网

https://github.com/therecipe/qt](https://github.com/therecipe/qt

安装可执行文件

在终端执行以下命令

# Go的环境变量配置,配置过一次就不用在设置了
go env -w GO111MODULE=on
go env -w GOPROXY=https://goproxy.cn

# 下载therecipe/qt库
go get -v -tags=no_env github.com/therecipe/qt/cmd/...

安装成功会在GOBIN目录下增加对应的qt可执行文件


qt

编译

在终端依次执行以下命令

# 设置环境变量
export QT_DIR=/Users/tickstep/Applications/Qt5.13.0
export QT_VERSION=5.13.0
export GOARCH=amd64

# 编译
qtsetup

编译成功会输出类似以下内容,等待编译完成即可。


qtsetup
Demo工程

源码

新建一个demo工程,main源码如下

package main

import (
    "os"
    "github.com/therecipe/qt/widgets"
)

func main() {

    // needs to be called once before you can start using the QWidgets
    app := widgets.NewQApplication(len(os.Args), os.Args)

    // create a window
    // with a minimum size of 250*200
    // and sets the title to "Hello Widgets Example"
    window := widgets.NewQMainWindow(nil, 0)
    window.SetMinimumSize2(250, 200)
    window.SetWindowTitle("Hello Widgets Example")

    // create a regular widget
    // give it a QVBoxLayout
    // and make it the central widget of the window
    widget := widgets.NewQWidget(nil, 0)
    widget.SetLayout(widgets.NewQVBoxLayout())
    window.SetCentralWidget(widget)

    // create a line edit
    // with a custom placeholder text
    // and add it to the central widgets layout
    input := widgets.NewQLineEdit(nil)
    input.SetPlaceholderText("Write something ...")
    widget.Layout().AddWidget(input)

    // create a button
    // connect the clicked signal
    // and add it to the central widgets layout
    button := widgets.NewQPushButton2("and click me!", nil)
    button.ConnectClicked(func(bool) {
        widgets.QMessageBox_Information(nil, "OK", input.Text(), widgets.QMessageBox__Ok, widgets.QMessageBox__Ok)
    })
    widget.Layout().AddWidget(button)

    // make the window visible
    window.Show()

    // start the main Qt event loop
    // and block until app.Exit() is called
    // or the window is closed by the user
    app.Exec()
}

编译demo源码

在终端执行以下命令

# 设置环境变量
export QT_DIR=/Users/tickstep/Applications/Qt5.13.0
export QT_VERSION=5.13.0
export GOARCH=amd64

# 编译
qtdeploy build desktop ./

编译成功会在deploy目录下生成对应的app文件


app

测试

双击app文件打开进行测试


测试app
总结

总的来说,在golang下使用qt进行gui开发不是一个很好的选择。如果你正好会qt和golang并且想尝鲜或者正好想做个跨平台的小工具,那么therecipe/qt算是一个比较好的选择。