Qt qml - 在没有任何条件的情况下运行一行(while(true))

Qt qml - run a line without any conditions (while(true))

本文关键字:true 运行 一行 情况下 while qml 条件 任何 Qt      更新时间:2023-10-16

我是qml中的菜鸟。我正在使用 CircularGauge 类,我想不断更新该值。我在网上找到的当前代码仅在按下某个键(第 7 行(时更改值。但是,我希望无论如何更新值(类似于 c++ 中的 while(true(。在第 7 行中,仪表板是用 C++ 定义的类,类成员函数将从硬件中获取值。

CircularGauge {
scale : 0.7
value: accelerating ? maximumValue : 0
anchors.centerIn: parent
property bool accelerating: false
Keys.onPressed: {
value = Dashboard.getSpeed();
}
}

还是没有运气。更新后的代码为:

Window {    
x: 100 
y: 100
width: 190 
height: 190
visible: true
MouseArea {
anchors.fill: parent
onClicked: {
Qt.quit();
}
}
CircularGauge {
scale : 0.7
anchors.centerIn: parent
Timer {
interval: 50
running: true
repeat: true
onTriggered: value = Dashboard.getSpeed()
}
Component.onCompleted: forceActiveFocus()
Behavior on value {
NumberAnimation {
duration: 100
}
}
}

}

解决:

Window {    
x: 100 
y: 100
width: 190 
height: 190
visible: true
CircularGauge {
scale : 0.7
anchors.centerIn: parent
id: dashboard
Timer {
interval: 40
running: true
repeat: true
onTriggered: dashboard.value = Dashboard.getSpeed()
}
}
}

您是否考虑过使用Timer元素以特定间隔连续执行代码?

Timer {
interval: 100
running: true
repeat: true
onTriggered: doYourStuff()
}

您绝对不希望像while(true)这样的东西(除非您有手动退出点(,因为这会阻塞线程,因此您的应用程序将有效地挂起。

还要考虑到,当你value = something的那一刻,你将打破你所拥有的value的现有绑定。

尝试这样的事情:

CircularGauge {
scale : 0.7
anchors.centerIn: parent
Timer {
interval: 100
running: true
repeat: true
onTriggered: value = value ? 0 : Dashboard.getSpeed()
}
}

它将做的是每 100 毫秒将值设置为 0(如果当前值不是 0(,或者设置为Dashboard.getSpeed().

好的,您进行了另一项更改,如果您只想不断更新值,那么计时器触发器处理程序所需的只是:

onTriggered: value = Dashboard.getSpeed()

但是更正确的设计是在Dashboard类中有一个speedQ_PROPERTY,并实现值更改通知,那么在QML中您需要做的就是:

CircularGauge {
value: Dashboard.speed
}

理想情况下,可以设置仪表板的更新频率,并且它仍将使用计时器,但使用QTimerC++ 类。