用Qcanvse画图,画图并且到使其随机移动效果如下
下面是实现的代码:
工程文件MouseMove.pro
#####################################################################
# Automatically generated by qmake (1.07a) Thu Dec 15 11:19:45 2011
#####################################################################
TEMPLATE = app
INCLUDEPATH += .
MOC_DIR += .moc
OBJECTS_DIR += .tmp
# Input
HEADERS += main.h
SOURCES += main.cpp
这里是main头文件
main.h
#include <qapplication.h>
#include <qcanvas.h>
#include <qfont.h>
#include <qp_w_picpath.h>
#include <qtimer.h>
#include <math.h>
class View : public QCanvasView
{
Q_OBJECT
public:
View(QCanvas& canvas);
protected:
void contentsMousePressEvent(QMouseEvent *e);
void Advance();
public slots:
virtual void change();
private:
QCanvasPolygon *p;
QCanvasRectangle *r;
QCanvasText *t;
QTimer *tm;
double m_x;
double m_y;
};
程序源文件
mian.cpp
#include <qapplication.h>
#include <main.h>
View::View(QCanvas& canvas) : QCanvasView(&canvas),m_x(0),m_y(0)
{
canvas.setBackgroundPixmap(QPixmap("logo.jpg"));
canvas.resize(370, 300);
canvas.setAdvancePeriod(30);
p = new QCanvasPolygon(&canvas); // 多边行
QPointArray a;
a.setPoints(3, 50, 100, 200, 200, 50, 200);
p->setVelocity(0.5,-0.5);
p->setPoints(a);
p->setBrush(Qt::blue);
p->setZ(10); // 深度
p->show(); // 显示绘图物件
r = new QCanvasRectangle(100, 100, 50, 100, &canvas);// 四方形
r->setBrush(Qt::red);
r->setZ(10);
r->show();
t = new QCanvasText("What will you study today? ^o^", &canvas); // 文字
t->setFont(QFont("Helvetica", 12, QFont::Bold));
t->setVelocity(0.5,0.5);
t->setColor(Qt::blue);
t->setZ(20);
t->setTextFlags(AlignBottom);
t->move(5, 20);
t->show();
tm = new QTimer(this);
connect(tm, SIGNAL(timeout()),this,SLOT(change()));
tm->start(1000);
}
void View::contentsMousePressEvent(QMouseEvent *e)
{
r->move(e->pos().x(), e->pos().y());
t->move(0,10);
}
void View::Advance()
{
qDebug("jj");
if(t->x()>370)
t->move(0,0);
}
void View::change() //设置移动速度
{
r->move(rand()%10, rand()%10);
t->move(rand()%10, rand()%10);
p->move(rand()%10, rand()%10);
m_x = rand()%10;
m_y = rand()%10;
r->setVelocity(m_x, m_y); // 移动速度
}
这是主函数
int main(int argc, char** argv)
{
QApplication app(argc, argv);
QCanvas canvas(0, 0);
canvas.setAdvancePeriod(30); // 移动更新时间间隔:
canvas.setDoubleBuffering(true); // double buffer
View c(canvas);
app.setMainWidget(&c);
c.show();
return app.exec();
}
这里设置了移动的物体,速度,还设置了开始位置