Get user input from QML using go-qml

I am trying to get user input from qml using package gopkg.in/qml.v1

. Setting values โ€‹โ€‹from Go completed successfully. But I cannot get the changed values โ€‹โ€‹back. For example, I have set Name from go code to qml. After the user changes the textbox and clicks the button, I read the user input and click"Hello, " + ctrl.Name

This is an example:

main.go

package main

import (
    "fmt"
    "gopkg.in/qml.v1"
    "os"
)

func main() {
    if err := qml.Run(run); err != nil {
        fmt.Fprintf(os.Stderr, "error: %v\n", err)
        os.Exit(1)
    }
}

func run() error {
    engine := qml.NewEngine()

    component, err := engine.LoadFile("main.qml")
    if err != nil {
        return err
    }

    context := engine.Context()
    context.SetVar("ctrl", &Control{Name: "Enter your name"})

    window := component.CreateWindow(nil)

    window.Show()
    window.Wait()

    return nil
}

type Control struct {
    Name    string
    Message string
}

func (ctrl *Control) Hello() {
    go func() {
        ctrl.Message = "Hello, " + ctrl.Name
        qml.Changed(ctrl, &ctrl.Message)
    }()
}

      

main.qml

import QtQuick 2.0
import QtQuick.Controls 1.1

Rectangle {
    id: root
    color: "#ffffff"

    width: 320
    height: 320

    TextEdit {
        id: textEdit1
        x: 8
        y: 8
        width: 304
        height: 20
        text: ctrl.name
        font.pixelSize: 12
    }

    Button {
        id: button1
        x: 8
        y: 34
        width: 304
        height: 27
        text: qsTr("Button")
        onClicked: {
            ctrl.hello()
        }
    }

    Text {
        id: text1
        x: 8
        y: 67
        width: 304
        height: 23
        text: ctrl.message
        font.pixelSize: 12
    }
}

      

To make this work, I have to add an explicit assignment to the Button's onClicked () like this:

Button {
    id: button1
    x: 8
    y: 34
    width: 304
    height: 27
    text: qsTr("Button")
    onClicked: {
        ctrl.name = textEdit1.text
        ctrl.hello()
    }
}

      

How am I wrong? Thanks you

+3


source to share


1 answer


You must use the binding to update ctrl.name

, otherwise it stays the same:

TextEdit {
    id: textEdit1
    x: 8
    y: 8
    width: 304
    height: 20
    text: ctrl.name
    font.pixelSize: 12
}
Binding { target: ctrl; property: "name"; value: textEdit1.text }

      



ref: http://qt-project.org/doc/qt-5/qml-qtqml-binding.html

+4


source







All Articles