太高興了,搞了快2天才知道動畫原理,我新增了一個QThread的Class,然後要在此Class作一個信號槽(SIGNAL),連到
QWidget的SlOT,一直沒注意到應該跟QTimer類似,才想很久才想通,當然用QTimer也可達到動畫效果,只是我要用QThread來達成,彈性較大
Wthread.h
--------------------------------------------------------------------------
#ifndef WTHREAD_H
#define WTHREAD_H
#include
class Wthread:public QThread
{
Q_OBJECT
public:
Wthread(QObject *parent = 0);
~Wthread();
//信號
signals:
void setxy(int i1, int i2,int i3,int i4);
protected:
void run();
};
#endif // WTHREAD_H
----------------------------------------------------------------------------
Wthread.cpp
----------------------------------------------------------------
#include "wthread.h"
#include
Wthread::Wthread(QObject *parent)
: QThread(parent)
{
}
void Wthread::run() {
for(int i = 10; i 300; i += 10) {
emit setxy(i,i,i,i);
msleep(1000);
}
}
Wthread::~Wthread()
{
}
--------------------------------------------------------------------
Widget.cpp
----------------------------------------------------------------------------
#include "widget.h"
#include "ui_widget.h"
#include
#include
#include
#include
#include
#include "wthread.h"
Widget::Widget(QWidget *parent)
: QWidget(parent), ui(new Ui::Widget)
{
ui->setupUi(this);
setShape(20,20,120,120);
step_value=0;
//qRegisterMetaType
connect(&thread, SIGNAL(setxy(int , int ,int ,int )),this, SLOT(setShape(int ,int ,int ,int )));
}
Widget::~Widget()
{
delete ui;
}
//重畫
void Widget::setShape(int x,int y,int w,int h)
{
shapex=x;
shapey=y;
shape_width=w;
shape_height=h;
update();
}
void Widget::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
QPainterPath path;
painter.setBrush(QColor(122, 163, 39));
path.addRect(shapex, shapey, shape_width, shape_height);
painter.drawPath(path);
}
void Widget::on_pushButton_pressed()
{
step_value= step_value+10;
setShape(20,20,120+step_value,120+step_value);
}
void Widget::on_pushButton_2_pressed()
{
step_value= step_value-10;
setShape(20,20,120+step_value,120+step_value);
}
void Widget::on_pushButton_3_pressed()
{
thread.start();
}
又作一個,做在QFrame裡面
重前面幾段,就可完成一個動畫,又能一邊控制物件移動,就可用Qt來作簡單的遊戲了,來看下面的例子
沒有留言:
張貼留言