效果是红色图形每隔一秒移动一次,循环在窗口绕圈圈
头文件,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"
}
}