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 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥15 pyqt信号槽连接写法
  • ¥500 把面具戴到人脸上,请大家贡献智慧,别用大模型回答,大模型的答案没啥用
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。