Qt/QML学习-定时器

QML学习

main.qml

Window {
    width: 640
    height: 480
    visible: true
    title: qsTr("Hello World")

    Rectangle {
        id: myRectangle
        anchors.fill: parent
        color: "#ff0000"
        Switch {
            anchors.centerIn: parent
            text: "启动定时器"
            checked: false
            onCheckedChanged: {
                if (checked){
                    myTimer.start()
                    text = "停止定时器"
                } else {
                    myTimer.stop()
                    text = "启动定时器"
                }
            }
        }
    }

    Timer {
        id: myTimer
        interval: 500
        repeat: true
        running: false
        onTriggered: {
            myRectangle.color =
                    (myRectangle.color == "#ff0000")
                    ? "#0000ff" : "#ff0000"
        }
    }
}

演示

视频讲解

Qt中,可以通过定时器来实现QML和后端的定时器同步。具体来说,可以在后端代码中创建一个定时器,然后在QML代码中监听该定时器的信号,从而实现QML和后端的定时器同步。 下面是一个简单的示例代码: 后端代码: ```cpp class MyBackend : public QObject { Q_OBJECT public: MyBackend(QObject* parent = nullptr) : QObject(parent) { // 创建定时器 m_timer = new QTimer(this); m_timer->setInterval(1000); // 设置定时器间隔为1秒 connect(m_timer, &QTimer::timeout, this, &MyBackend::onTimerTimeout); m_timer->start(); // 启动定时器 } signals: void timerTick(); // 定义定时器信号 private slots: void onTimerTimeout() { emit timerTick(); // 发出定时器信号 } private: QTimer* m_timer; }; ``` QML代码: ```qml import QtQuick 2.0 Item { width: 200 height: 200 Text { id: text text: "0" font.pixelSize: 30 anchors.centerIn: parent } Connections { target: myBackend // 监听后端定时器信号 onTimerTick: { text.text = parseInt(text.text) + 1 // 更新文本内容 } } Component.onCompleted: { myBackend.timerTick.connect(function() { }) // 连接定时器信号 } MyBackend { id: myBackend } } ``` 在上述代码中,后端代码中创建了一个定时器,并定义了一个自定义信号`timerTick()`。在QML代码中,通过`Connections`对象监听了该信号,并在接收到信号后更新了文本内容。同时,在QML代码的`Component.onCompleted`信号中,连接了后端代码的定时器信号。 这样,QML和后端的定时器就实现了同步。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值