qml定时器示例

效果是红色图形每隔一秒移动一次,循环在窗口绕圈圈

头文件,qml文件要加入到资源文件哦

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QQuickWidget>
#include <QQmlContext>

class Widget : public QWidget
{
    Q_OBJECT 

//使得qml可以引用widget的属性,大概的意思是窗口大小改变发出RectChanged信号,然后返回改变后的大小width和height赋值给_width,_height
    Q_PROPERTY(int _width READ returnW NOTIFY RectChanged)
    Q_PROPERTY(int _height READ retrunH NOTIFY RectChanged)
public:
    Widget(QWidget *parent = 0);
    ~Widget();

    int returnW(){return _width = width();}
    int retrunH(){return _height = height();}

    void resizeEvent(QResizeEvent *event);

signals:
    void RectChanged();
private:
    QQuickWidget *qmlWidget;
    int _width, _height;
};

#endif // WIDGET_H


//源文件
#include "widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    qmlWidget = new QQuickWidget(this);
    qmlWidget->rootContext()->setContextProperty("View",this);
    qmlWidget->setSource(QUrl(QStringLiteral("qrc:/Timer.qml")));
    resize(700,500);
}

Widget::~Widget()
{
    if(qmlWidget)
    {
        delete qmlWidget;
        qmlWidget = NULL;
    }
}

void Widget::resizeEvent(QResizeEvent *event)
{
    emit RectChanged();
}

//qml文件

import QtQuick 2.0
import QtQuick.Controls 1.4

Rectangle {
    id: root
    width: View._width
    height: View._height
    color: "green"

    Rectangle {
        id: rect
        x: 0; y: 0
        width: 50
        height: 50
        color: "red"
    }

    property var walk: false
    Timer {
        id: timer
        interval: 1000
	//这个属性设置为true才能每隔1秒触发一次onTriggered.
        repeat: true
        onTriggered: {
            if(rect.x+50 < root.width && !walk)
            {
                rect.x += 50;
            }else
            {
                if(rect.y+50<root.height && !walk)
                {
                    rect.y += 50;
                }else
                {
                    walk = true;
                    if(rect.x-50>0)
                    {
                        rect.x -= 50;
                    }else
                    {
                        if(rect.y-50>0)
                        {
                            rect.y -= 50;
                        }else
                        {
                            walk = false;
                        }
                    }
                }
            }

        }
    }

    Button {
        anchors.centerIn: parent
        onClicked: timer.start()
        text: "Start"
    }
}

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值