QML_定时器

QML_定时器

定时器的属性:
intercal:int-设置触发间隔,单位:ms。默认的间隔为1000ms
repect:bool-设置为true,则会重复触发定时器;设置为false,则只触发一次就停止。默认设置为false
running:bool-设置为true,则启动定时器;设置为false,则停止定时器。默认为false
triggeredOnStart:bool-设置为true,则定时器在启动后立即触发,然后再在指定的时间间隔触发;设置为false,则触发器触发两次,一次是启动后,一次是周期后。默认为false
定时器的信号:
定时器只有一个信号——triggered() 定时器被触发后,对应的处理程序为onTriggered()
定时器的方法:
start()-启动定时器。如果定时器已经在运行,则调用此方法无效
restart()-重启定时器,如果定时器没有运行,它将被启动,否则它将重置到初始状态并启动
stop()-停止定时器

1、循环定时器的简单应用

Window {
    id: window
    visible: true
    width: 800
    height: 480
    title: qsTr("Hello World")

    Rectangle {
        id: rect
        anchors.fill: parent
        color: "green"

        Rectangle {
            id: rect1
            x: 0
            y: 0
            width: 50
            height: 480
            color: "orange"
        }
    }

    Timer {
        id: time
        interval: 1000
        repeat: true
        running: true
        onTriggered: {
            if (rect1.x + rect1.width < rect.width) {
                rect1.x += 50
            } else {
                rect1.x = 0
            }
        }
    }
}

2、制作一个简单地界面计时器
注意:triggeredOnStart: true是调用time.start()才开始,而running: true是直接就开始

Window {
    id: window
    visible: true
    width: 800
    height: 480
    title: qsTr("Hello World")

    Text {
        id: text
        anchors.centerIn: parent
        color: "red"
        text: "10"
        font.pixelSize: 50
        property int num: 10
    }

    Timer {
        id: time
        interval: 1000
        repeat: true
        triggeredOnStart: true  
        onTriggered: {
            text.text = text.num
            text.num--
            if (text.num < 0) {
                time.stop()
                text.text = "计时结束"
            }
        }
    }

    Button {
        id: start
        anchors.top: text.bottom
        anchors.topMargin: 100
        x: 170
        text: "start"
        onClicked: {
            time.start()
        }
    }

    Button {
        id: restart
        anchors.top: text.bottom
        anchors.topMargin: 100
        anchors.left: start.right
        anchors.leftMargin: 10
        text: "restart"
        onClicked: {
            time.start()
            text.num = 10
        }
    }

    Button {
        id: stop
        anchors.top: text.bottom
        anchors.topMargin: 100
        anchors.left: restart.right
        anchors.leftMargin: 10
        text: "stop"
        onClicked: {
            time.stop()
        }
    }
}

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值