qml

package module
v0.0.0-...-105c90b Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 20, 2014 License: LGPL-3.0 Imports: 19 Imported by: 0

README

QML support for the Go language

This is an ALPHA release

This package is in an alpha stage, and still in heavy development. APIs may change, and things may break.

At this time contributors and developers that are interested in tracking the development closely are encouraged to use it. If you'd prefer a more stable release, please hold on a bit and subscribe to the mailing list for news. It's in a pretty good state, so it shall not take too long.

Demos

These introductory videos demonstrate the use of Go QML:

Community

Please join the mailing list for following relevant development news and discussing project details.

Documentation

The introductory documentation as well as the detailed API documentation is available at gopkg.in/v0/qml.

Installation

To try the alpha release you'll need:

  • Go 1.2 (release candidate), for the C++ support of go build
  • Qt 5.0.X or 5.1.X with the development files
  • The Qt headers qmetaobject_p.h and qmetaobjectbuilder_p.h, for the dynamic meta object support

See below for more details about getting these requirements installed in different environments and operating systems.

After the requirements are satisfied, go get should work as usual:

go get gopkg.in/v0/qml

Requirements on Ubuntu

If you are using Ubuntu, the Ubuntu SDK will take care of the Qt dependencies:

$ sudo add-apt-repository ppa:ubuntu-sdk-team/ppa
$ sudo apt-get update
$ sudo apt-get install ubuntu-sdk qtbase5-private-dev qtdeclarative5-private-dev libqt5opengl5-dev

and Go 1.2 may be installed using godeb:

$ # Pick the right one for your system: 386 or amd64
$ ARCH=amd64
$ wget -q https://godeb.s3.amazonaws.com/godeb-$ARCH.tar.gz
$ tar xzvf godeb-$ARCH.tar.gz
godeb
$ sudo mv godeb /usr/local/bin
$ godeb list | head -1
1.2rc1
$ godeb install 1.2rc1
$ go get gopkg.in/v0/qml

Requirements on Mac OS X

On Mac OS X you'll need gcc (not a symlinked clang, as it complains about -std=c++11), and must specify the CXX, PKG_CONFIG_PATH, and CGO_CPPFLAGS environment variables.

Something along these lines should be effective:

$ brew tap homebrew/versions
$ brew install gcc48 qt5

$ export PKG_CONFIG_PATH=`brew --prefix qt5`/lib/pkgconfig
$ QT5VERSION=`pkg-config --modversion Qt5Core`
$ # For "private/qmetaobject_p.h" inclusion
$ export CGO_CPPFLAGS=-I`brew --prefix qt5`/include/QtCore/$QT5VERSION/QtCore
$ CXX=g++-4.8 go get gopkg.in/v0/qml

For Mac OS X Mavericks you may need to use brew install qt5 --HEAD and check that QT5VERSION is something reasonable like 5.2.0, ls /usr/local/Cellar/qt5/HEAD/include/QtCore/ | grep '^5' should also work.

Requirements on Windows

On Windows you'll need the following:

Then, assuming Qt was installed under C:\Qt5.1.1\, set up the following environment variables in the respective configuration:

CPATH += C:\Qt5.1.1\5.1.1\mingw48_32\include;C:\Qt5.1.1\5.1.1\mingw48_32\include\QtCore\5.1.1\QtCore
LIBRARY_PATH += C:\Qt5.1.1\5.1.1\mingw48_32\lib
PATH += C:\Qt5.1.1\5.1.1\mingw48_32\bin

After reopening the shell for the environment changes to take effect, this should work:

go get gopkg.in/v0/qml

Requirements everywhere else

If your operating system does not offer these dependencies readily, you may still have success installing Go 1.2rc1 and Qt 5.0.2 directly from the upstreams.

Documentation

Overview

Package qml offers graphical QML application support for the Go language.

Attention

This package is in an alpha stage, and still in heavy development. APIs may change, and things may break.

At this time contributors and developers that are interested in tracking the development closely are encouraged to use it. If you'd prefer a more stable release, please hold on a bit and subscribe to the mailing list for news. It's in a pretty good state, so it shall not take too long.

See http://github.com/go-qml/qml for details.

Introduction

The qml package enables Go programs to display and manipulate graphical content using Qt's QML framework. QML uses a declarative language to express structure and style, and supports JavaScript for in-place manipulation of the described content. When using the Go qml package, such QML content can also interact with Go values, making use of its exported fields and methods, and even explicitly creating new instances of registered Go types.

A simple Go application that integrates with QML may perform the following steps for offering a graphical interface:

  • Initialize the qml package (see Init)
  • Create an engine for loading and running QML content (see NewEngine)
  • Make Go values and types available to QML (see Context.SetVar and RegisterType)
  • Load QML content (see Engine.LoadString and Engine.LoadFile)
  • Create a new window for the content (see Component.CreateWindow)
  • Show the window and wait for it to be closed (see Window.Show and Window.Wait)

Some of these topics are covered below, and may also be observed in practice in the following examples:

https://github.com/go-qml/qml/tree/master/examples

Handling QML objects in Go

Any QML object may be manipulated by Go via the Object interface. That interface is implemented both by dynamic QML values obtained from a running engine, and by Go types in the qml package that represent QML values, such as Window, Context, and Engine.

For example, the following logic creates a window and prints its width whenever it's made visible:

win := component.CreateWindow(nil)
win.On("visibleChanged", func(visible bool) {
    if (visible) {
        fmt.Println("Width:", win.Int("width"))
    }
})

Information about the methods, properties, and signals that are available for QML objects may be obtained in the Qt documentation. As a reference, the "visibleChanged" signal and the "width" property used in the example above are described at:

http://qt-project.org/doc/qt-5.0/qtgui/qwindow.html

When in doubt about what type is being manipulated, the Object.TypeName method provides the type name of the underlying value.

Publishing Go values to QML

The simplest way of making a Go value available to QML code is setting it as a variable of the engine's root context, as in:

context := engine.Context()
context.SetVar("person", &Person{Name: "Ale"})

This logic would enable the following QML code to successfully run:

import QtQuick 2.0
Item {
    Component.onCompleted: console.log("Name is", person.name)
}

Publishing Go types to QML

While registering an individual Go value as described above is a quick way to get started, it is also fairly limited. For more flexibility, a Go type may be registered so that QML code can natively create new instances in an arbitrary position of the structure. This may be achieved via the RegisterType function, as the following example demonstrates:

qml.RegisterTypes("GoExtensions", 1, 0, []qml.TypeSpec{{
    Init: func(p *Person, obj qml.Object) { p.Name = "<none>" },
}})

With this logic in place, QML code can create new instances of Person by itself:

import QtQuick 2.0
import GoExtensions 1.0
Item{
    Person {
        id: person
        name: "Ale"
    }
    Component.onCompleted: console.log("Name is", person.name)
}

Lowercasing of names

Independently from the mechanism used to publish a Go value to QML code, its methods and fields are available to QML logic as methods and properties of the respective QML object representing it. As required by QML, though, the Go method and field names are lowercased according to the following scheme when being accesed from QML:

value.Name      => value.name
value.UPPERName => value.upperName
value.UPPER     => value.upper

Setters and getters

While QML code can directly read and write exported fields of Go values, as described above, a Go type can also intercept writes to specific fields by declaring a setter method according to common Go conventions. This is often useful for updating the internal state or the visible content of a Go-defined type.

For example:

type Person struct {
    Name string
}

func (p *Person) SetName(name string) {
    fmt.Println("Old name is", p.Name)
    p.Name = name
    fmt.Println("New name is", p.Name)
}

In the example above, whenever QML code attempts to update the Person.Name field via any means (direct assignment, object declarations, etc) the SetName method is invoked with the provided value instead.

A setter method may also be used in conjunction with a getter method rather than a real type field. A method is only considered a getter in the presence of the respective setter, and according to common Go conventions it must not have the Get prefix.

Inside QML logic, the getter and setter pair is seen as a single object property.

Painting

Custom types implemented in Go may have displayable content by defining a Paint method such as:

func (p *Person) Paint(painter *qml.Painter) {
    // ... OpenGL calls with the gopkg.in/v0/qml/gl package ...
}

A simple example is available at:

https://github.com/go-qml/qml/tree/master/examples/painting

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Changed

func Changed(value, fieldAddr interface{})

Changed notifies all QML bindings that the given field value has changed.

For example:

qml.Changed(&value, &value.Field)

func CollectStats

func CollectStats(enabled bool)

func Flush

func Flush()

Flush synchronously flushes all pending QML activities.

func Init

func Init(options *InitOptions)

Init initializes the qml package with the provided parameters. If the options parameter is nil, default options suitable for a normal graphic application will be used.

Init must be called only once, and before any other functionality from the qml package is used.

func Lock

func Lock()

Lock freezes all QML activity by blocking the main event loop. Locking is necessary before updating shared data structures without race conditions.

It's safe to use qml functionality while holding a lock, as long as the requests made do not depend on follow up QML events to be processed before returning. If that happens, the problem will be observed as the application freezing.

The Lock function is reentrant. That means it may be called multiple times, and QML activities will only be resumed after Unlock is called a matching number of times.

func RegisterConverter

func RegisterConverter(typeName string, converter func(engine *Engine, obj Object) interface{})

RegisterConverter registers the convereter function to be called when a value with the provided type name is obtained from QML logic. The function must return the new value to be used in place of the original value.

func RegisterTypes

func RegisterTypes(location string, major, minor int, types []TypeSpec)

RegisterTypes registers the provided list of type specifications for use by QML code. To access the registered types, they must be imported from the provided location and major.minor version numbers.

For example, with a location "GoExtensions", major 4, and minor 2, this statement imports all the registered types in the module's namespace:

import GoExtensions 4.2

See the documentation on QML import statements for details on these:

http://qt-project.org/doc/qt-5.0/qtqml/qtqml-syntax-imports.html

func ResetStats

func ResetStats()

func RunMain

func RunMain(f func())

RunMain runs f in the main QML thread and waits for f to return.

This is meant for extensions that integrate directly with the underlying QML logic.

func SetLogger

func SetLogger(logger interface{})

SetLogger sets the target for messages logged by the qml package, including console.log and related calls from within qml code.

The logger value must implement either the StdLogger interface, which is satisfied by the standard *log.Logger type, or the QmlLogger interface, which offers more control over the logged message.

If no logger is provided, the qml package will send messages to the default log package logger. This behavior may also be restored by providing a nil logger to this function.

func Unlock

func Unlock()

Unlock releases the QML event loop. See Lock for details.

Types

type Common

type Common struct {
	// contains filtered or unexported fields
}

Common implements the common behavior of all QML objects. It implements the Object interface.

func CommonOf

func CommonOf(addr unsafe.Pointer, engine *Engine) *Common

CommonOf returns the Common QML value for the QObject at addr.

This is meant for extensions that integrate directly with the underlying QML logic.

func (*Common) Addr

func (obj *Common) Addr() uintptr

Addr returns the QML object address.

This is meant for extensions that integrate directly with the underlying QML logic.

func (*Common) Bool

func (obj *Common) Bool(property string) bool

Bool returns the bool value of the named property. Bool panics if the property is not a bool.

func (*Common) Call

func (obj *Common) Call(method string, params ...interface{}) interface{}

Call calls the given object method with the provided parameters. Call panics if the method does not exist.

func (*Common) Color

func (obj *Common) Color(property string) color.RGBA

Color returns the RGBA value of the named property. Color panics if the property is not a color.

func (*Common) Common

func (obj *Common) Common() *Common

Common returns obj itself.

This provides access to the underlying *Common for types that embed it, when these are used via the Object interface.

func (*Common) Create

func (obj *Common) Create(ctx *Context) Object

Create creates a new instance of the component held by obj. The component instance runs under the ctx context. If ctx is nil, it runs under the same context as obj.

The Create method panics if called on an object that does not represent a QML component.

func (*Common) CreateWindow

func (obj *Common) CreateWindow(ctx *Context) *Window

CreateWindow creates a new instance of the component held by obj, and creates a new window holding the instance as its root object. The component instance runs under the ctx context. If ctx is nil, it runs under the same context as obj.

The CreateWindow method panics if called on an object that does not represent a QML component.

func (*Common) Destroy

func (obj *Common) Destroy()

Destroy finalizes the value and releases any resources used. The value must not be used after calling this method.

func (*Common) Float64

func (obj *Common) Float64(property string) float64

Float64 returns the float64 value of the named property. Float64 panics if the property cannot be represented as float64.

func (*Common) Int

func (obj *Common) Int(property string) int

Int returns the int value of the named property. Int panics if the property cannot be represented as an int.

func (*Common) Int64

func (obj *Common) Int64(property string) int64

Int64 returns the int64 value of the named property. Int64 panics if the property cannot be represented as an int64.

func (*Common) Interface

func (obj *Common) Interface() interface{}

Interface returns the underlying Go value that is being held by the object wrapper.

It is a runtime error to call Interface on values that are not backed by a Go value.

func (*Common) List

func (obj *Common) List(property string) *List

List returns the list value of the named property. List panics if the property is not a list.

func (*Common) Map

func (obj *Common) Map(property string) *Map

Map returns the map value of the named property. Map panics if the property is not a map.

func (*Common) Object

func (obj *Common) Object(property string) Object

Object returns the object value of the named property. Object panics if the property is not a QML object.

func (*Common) ObjectByName

func (obj *Common) ObjectByName(objectName string) Object

ObjectByName returns the Object value of the descendant object that was defined with the objectName property set to the provided value. ObjectByName panics if the object is not found.

func (*Common) On

func (obj *Common) On(signal string, function interface{})

On connects the named signal from obj with the provided function, so that when obj next emits that signal, the function is called with the parameters the signal carries.

The provided function must accept a number of parameters that is equal to or less than the number of parameters provided by the signal, and the resepctive parameter types must match exactly or be conversible according to normal Go rules.

For example:

obj.On("clicked", func() { fmt.Println("obj got a click") })

Note that Go uses the real signal name, rather than the one used when defining QML signal handlers ("clicked" rather than "onClicked").

For more details regarding signals and QML see:

http://qt-project.org/doc/qt-5.0/qtqml/qml-qtquick2-connections.html

func (*Common) Property

func (obj *Common) Property(name string) interface{}

Property returns the current value for a property of the object. If the property type is known, type-specific methods such as Int and String are more convenient to use. Property panics if the property does not exist.

func (*Common) Set

func (obj *Common) Set(property string, value interface{})

Set changes the named object property to the given value.

func (*Common) String

func (obj *Common) String(property string) string

String returns the string value of the named property. String panics if the property is not a string.

func (*Common) TypeName

func (obj *Common) TypeName() string

TypeName returns the underlying type name for the held value.

type Context

type Context struct {
	Common
}

Context represents a QML context that can hold variables visible to logic running within it.

func (*Context) SetVar

func (ctx *Context) SetVar(name string, value interface{})

SetVar makes the provided value available as a variable with the given name for QML code executed within the c context.

If value is a struct, its exported fields are also made accessible to QML code as attributes of the named object. The attribute name in the object has the same name of the Go field name, except for the first letter which is lowercased. This is conventional and enforced by the QML implementation.

The engine will hold a reference to the provided value, so it will not be garbage collected until the engine is destroyed, even if the value is unused or changed.

func (*Context) SetVars

func (ctx *Context) SetVars(value interface{})

SetVars makes the exported fields of the provided value available as variables for QML code executed within the c context. The variable names will have the same name of the Go field names, except for the first letter which is lowercased. This is conventional and enforced by the QML implementation.

The engine will hold a reference to the provided value, so it will not be garbage collected until the engine is destroyed, even if the value is unused or changed.

func (*Context) Var

func (ctx *Context) Var(name string) interface{}

Var returns the context variable with the given name.

type Engine

type Engine struct {
	Common
	// contains filtered or unexported fields
}

Engine provides an environment for instantiating QML components.

func NewEngine

func NewEngine() *Engine

NewEngine returns a new QML engine.

The Destory method must be called to finalize the engine and release any resources used.

func (*Engine) AddImageProvider

func (e *Engine) AddImageProvider(prvId string, f func(imgId string, width, height int) image.Image)

AddImageProvider registers f to be called when an image is requested by QML code with the specified provider identifier. It is a runtime error to register the same provider identifier multiple times.

The imgId provided to f is the requested image source, with the "image:" scheme and provider identifier removed. For example, with an image image source of "image://myprovider/icons/home.ext", the respective imgId would be "icons/home.ext".

If either the width or the height parameters provided to f are zero, no specific size for the image was requested. If non-zero, the returned image should have the the provided size, and will be resized if the returned image has a different size.

See the documentation for more details on image providers:

http://qt-project.org/doc/qt-5.0/qtquick/qquickimageprovider.html

func (*Engine) Context

func (e *Engine) Context() *Context

Context returns the engine's root context.

func (*Engine) Destroy

func (e *Engine) Destroy()

Destroy finalizes the engine and releases any resources used. The engine must not be used after calling this method.

It is safe to call Destroy more than once.

func (*Engine) Load

func (e *Engine) Load(location string, r io.Reader) (Object, error)

Load loads a new component with the provided location and with the content read from r. The location informs the resource name for logged messages, and its path is used to locate any other resources referenced by the QML content.

Once a component is loaded, component instances may be created from the resulting object via its Create and CreateWindow methods.

func (*Engine) LoadFile

func (e *Engine) LoadFile(path string) (Object, error)

LoadFile loads a component from the provided QML file. Resources referenced by the QML content will be resolved relative to its path.

Once a component is loaded, component instances may be created from the resulting object via its Create and CreateWindow methods.

func (*Engine) LoadString

func (e *Engine) LoadString(location, qml string) (Object, error)

LoadString loads a component from the provided QML string. The location informs the resource name for logged messages, and its path is used to locate any other resources referenced by the QML content.

Once a component is loaded, component instances may be created from the resulting object via its Create and CreateWindow methods.

type InitOptions

type InitOptions struct {
}

InitOptions holds options to initialize the qml package.

type List

type List struct {
	// contains filtered or unexported fields
}

List holds a QML list which may be converted to a Go slice of an appropriate type via Convert.

In the future this will also be able to hold a reference to QML-owned maps, so they can be mutated in place.

func (*List) Convert

func (l *List) Convert(sliceAddr interface{})

Convert allocates a new slice and copies the list content into it, performing type conversions as possible, and then assigns the result to the slice pointed to by sliceAddr. Convert panics if the list values are not compatible with the provided slice.

func (*List) Len

func (l *List) Len() int

Len returns the number of elements in the list.

type LogMessage

type LogMessage interface {
	Severity() LogSeverity
	Text() string
	File() string
	Line() int

	String() string // returns "file:line: text"
	// contains filtered or unexported methods
}

LogMessage is implemented by values provided to QmlLogger.QmlOutput.

type LogSeverity

type LogSeverity int
const (
	LogDebug LogSeverity = iota
	LogWarning
	LogCritical
	LogFatal
)

type Map

type Map struct {
	// contains filtered or unexported fields
}

Map holds a QML map which may be converted to a Go map of an appropriate type via Convert.

In the future this will also be able to hold a reference to QML-owned maps, so they can be mutated in place.

func (*Map) Convert

func (m *Map) Convert(mapAddr interface{})

Convert allocates a new map and copies the content of m property to it, performing type conversions as possible, and then assigns the result to the map pointed to by mapAddr. Map panics if m contains values that cannot be converted to the type of the map at mapAddr.

func (*Map) Len

func (m *Map) Len() int

Len returns the number of pairs in the map.

type Object

type Object interface {
	Common() *Common
	Addr() uintptr
	TypeName() string
	Interface() interface{}
	Set(property string, value interface{})
	Property(name string) interface{}
	Int(property string) int
	Int64(property string) int64
	Float64(property string) float64
	Bool(property string) bool
	String(property string) string
	Color(property string) color.RGBA
	Object(property string) Object
	Map(property string) *Map
	List(property string) *List
	ObjectByName(objectName string) Object
	Call(method string, params ...interface{}) interface{}
	Create(ctx *Context) Object
	CreateWindow(ctx *Context) *Window
	Destroy()
	On(signal string, function interface{})
}

Object is the common interface implemented by all QML types.

See the documentation of Common for details about this interface.

type Painter

type Painter struct {
	// contains filtered or unexported fields
}

Painter is provided to Paint methods on Go types that have displayable content.

func (*Painter) Object

func (p *Painter) Object() Object

Object returns the underlying object being painted.

type QmlLogger

type QmlLogger interface {
	// QmlOutput is called whenever a new message is available for logging.
	// The message value must not be used after the method returns.
	QmlOutput(message LogMessage) error
}

The QmlLogger interface may be implemented to better control how log messages from the qml package are handled. Values that implement either StdLogger or QmlLogger may be provided to the SetLogger function.

type Statistics

type Statistics struct {
	EnginesAlive     int
	ValuesAlive      int
	ConnectionsAlive int
}

func Stats

func Stats() (snapshot Statistics)

type StdLogger

type StdLogger interface {
	// Output is called whenever a new message is available for logging.
	// See the standard log.Logger type for more details.
	Output(calldepth int, s string) error
}

The StdLogger interface is implemented by standard *log.Logger values. Values that implement either StdLogger or QmlLogger may be provided to the SetLogger function.

type TypeSpec

type TypeSpec struct {
	// Init must be set to a function that is called when QML code requests
	// the creation of a new value of this type. The provided function must
	// have the following type:
	//
	//     func(value *CustomType, object qml.Object)
	//
	// Where CustomType is the custom type being registered. The function will
	// be called with a newly created *CustomType and its respective qml.Object.
	Init interface{}

	// Name optionally holds the identifier the type is known as within QML code,
	// when the registered extension module is imported. If not specified, the
	// name of the Go type provided as the first argument of Init is used instead.
	Name string

	// Singleton defines whether a single instance of the type should be used
	// for all accesses, as a singleton value. If true, all properties of the
	// singleton value are directly accessible under the type name.
	Singleton bool
	// contains filtered or unexported fields
}

TypeSpec holds the specification of a QML type that is backed by Go logic.

The type specification must be registered with the RegisterTypes function before it will be visible to QML code, as in:

    qml.RegisterTypes("GoExtensions", 1, 0, []qml.TypeSpec{{
		Init: func(p *Person, obj qml.Object) {},
    }})

See the package documentation for more details.

type Window

type Window struct {
	Common
}

Window represents a QML window where components are rendered.

func (*Window) Hide

func (win *Window) Hide()

Hide hides the window.

func (*Window) PlatformId

func (win *Window) PlatformId() uintptr

PlatformId returns the window's platform id.

For platforms where this id might be useful, the value returned will uniquely represent the window inside the corresponding screen.

func (*Window) Root

func (win *Window) Root() Object

Root returns the root object being rendered.

If the window was defined in QML code, the root object is the window itself.

func (*Window) Show

func (win *Window) Show()

Show exposes the window.

func (*Window) Snapshot

func (win *Window) Snapshot() image.Image

Snapshot returns an image with the visible contents of the window. The main GUI thread is paused while the data is being acquired.

func (*Window) Wait

func (win *Window) Wait()

Wait blocks the current goroutine until the window is closed.

Directories

Path Synopsis
examples
gl
This package supports the implementation of the qml package, and must not be used by itself.
This package supports the implementation of the qml package, and must not be used by itself.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL