dongtaidai0492 2014-09-07 07:10
浏览 122
已采纳

使用go-qml从QML获取用户输入

I attempting to get user input from qml, using gopkg.in/qml.v1 package. Setting up values from Go is successful. But I can't get back changed values. For example, I set Name from go code to qml. After user change text field and push Button, I read user input and push back "Hello, " + ctrl.Name

This is 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
", 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 explicit assignment in Button onClicked() like this:

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

What I do wrong? Thank you

  • 写回答

1条回答 默认 最新

  • douyin2962 2014-09-07 14:13
    关注

    You have to use a 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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 Python安装cvxpy库出问题
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥15 python天天向上类似问题,但没有清零
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 C#调用python代码(python带有库)
  • ¥15 矩阵加法的规则是两个矩阵中对应位置的数的绝对值进行加和
  • ¥15 活动选择题。最多可以参加几个项目?
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题