Qt - 有没有办法提前触发定时器并将参数传递给定时器

Qt - Is there a way to trigger a Timer early and pass an argument into the Timer

我的应用程序的一部分 (Weather.qml) 目前使用计时器和 GPS 坐标每 5 分钟发出一次 HTTP GET 天气请求。我还有一个用户设置 (Settings.qml),允许用户选择一个位置。

我想知道是否可以在修改位置设置时触发计时器,并让计时器接收要传递到 HTTP Get 请求的新坐标。

目前,我只是将 GPS 坐标作为参数 (weatherLocation) 传递给启动时的可执行文件。

Weather.qml

WeatherForm {

    // A timer to refresh the forecast every 5 minutes
    Timer {
        interval: 300000
        repeat: true
        triggeredOnStart: true
        running: true
        onTriggered: {
            if (weatherAppKey != "" && weatherLocation != "") {
                // Make HTTP GET request and parse the result
                var xhr = new XMLHttpRequest;
                xhr.open("GET",
                         "https://api.darksky.net/forecast/"
                         + weatherAppKey + "/"
                         + weatherLocation
                         + "?exclude=[minutely,hourly,daily,alerts,flags]"
                         + "&units=auto");
                xhr.onreadystatechange = function() {
                    if (xhr.readyState == XMLHttpRequest.DONE) {
                        var a = JSON.parse(xhr.responseText);
                        parseWeatherData(a);
                    }
                }
                xhr.send();
            } else {

                ...

            }
        }
    }

    ...

}

Settings.qml

SettingsForm {

    Rectangle {

        ...

        ComboBox {
            id: cityComboBox
            anchors.right: parent.right
            anchors.verticalCenter: parent.Center
            model: ListModel {
                id: cbItems
                ListElement { city: "Vancouver"; coordinates: "49.2666,-123.1976" }
                ListElement { city: "New York"; coordinates: "40.7306,-73.9866" }
                ListElement { city: "Hong Kong"; coordinates: "22.2793,114.1628" }
            }
            textRole: 'city'

            // Trigger the Timer here possibly
            onCurrentIndexChanged: console.debug(cbItems.get(currentIndex).city)  
        }
    }
}

不可能也不需要。只需将坐标放在 属性 中,计时器可以引用它。您可以直接访问文件范围内的所有内容(委托中除外)。

I was wondering if it was possible to trigger the Timer whenever the location setting was modified

你可以,但这违背了使用计时器的目的 - 计时器是由经过的时间间隔触发的。但是,您可以重新启动并触发计时器,然后坐标会发生变化:

property string location : weatherLocation
...
onLocationChanged: timer.restart()

只需修改代码以使用 location 代替 weatherLocation。您可以通过以下方式更改位置:

onCurrentIndexChanged: location = cbItems.get(currentIndex).coordinates

如果您使 location 成为主要 qml 组件的 属性,它将可以从嵌套(直接或间接)在主要组件中的每个对象直接访问(除非它被隐藏同名源本地 属性).