Qt qml - 运行没有任何条件的行(while(true))

时间:2017-07-26 19:30:11

标签: c++ qt qml

我是qml中的菜鸟。我正在使用CircularGauge类,我想不断更新值。我在网上找到的当前代码仅在按下某个键时更改该值(第7行)。但是,我希望无论如何都要更新值(类似于c ++中的while(true)。在第7行中,dashboard是一个用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()
}
}
}

1 个答案:

答案 0 :(得分:1)

您是否考虑过使用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()
  }
}

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

好的,你做了另一个改变,如果你想要做的就是连续更新值,那么定时器触发器处理程序所需的只是:

onTriggered: value = Dashboard.getSpeed()

但更正确的设计是在speed课程中设置Q_PROPERTY Dashboard,并实施有关价值变化的通知,那么您在QML中需要做的就是这个:

CircularGauge {
  value: Dashboard.speed
}

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