Qt基于QGraphicsObject自定义图元并实现简单的动画
Qt 图形的绘制 可以是QPainter方法直接绘制,另一种方法就是通过继承QGraphicsItem类来定制自己的图元类,这样就可以根据自己的需求来制作它的形状、颜色、属性以及交互等。但是这样的图元会存在一个缺点,那就是不能使用Qt的信号/槽机制,也不能使用Qt属性系统,也不能使用Qt的动画框架实现动画。
在Qt已经考虑到了这些问题,QGraphicsObject应运而生。QGraphicsObject同时继承于QObject和QGraphicsItem。这样自定义图元既可以获得QGraphicsItem中写好的图元特性又能使用信号/槽机制方便信息传递,还可以使用Qt的动画框架。
动画框架的好处在于,在单线程的UI设计中,可以实现不同的图元的各自的动画效果。
举例;
实现这样的效果:在场景中添加自定义图元,利用QQPropertyAnimation 动画框架实现动画。
过程:
1、新建一个的项目,命名可以自定义 如graphicObjectDemo。
2、添加类tagObject :
注意:如果该类要使用信号机制,记得一定要勾选include QObject、Add Q_OBJECT 。
改写 tagObject.cpp
#include "tagobject.h"
#include <QPainter>
tagObject::tagObject()
{
brushColor = Qt::lightGray;
setFlag(QGraphicsItem::ItemIsFocusable);
setFlag(QGraphicsItem::ItemIsMovable);
}
QRectF tagObject::boundingRect() const
{
qreal adjust = 0.5;
return QRectF(-25 - adjust, -25 - adjust,
50 + adjust, 50 + adjust);
}
void tagObject::paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
QWidget *widget)
{
painter->setBrush(brushColor);
// 各个点的坐标
static const QPointF points[3] = {QPointF(-8, 8), QPointF(8, 8), QPointF(0,-8)};
painter->drawPolygon(points, 3);
}
tagOBject.h
#ifndef TAGOBJECT_H
#define TAGOBJECT_H
#include <QObject>
#include<QGraphicsObject>
class tagObject:public QGraphicsObject
{
Q_OBJECT
public:
tagObject();
QRectF boundingRect() const;
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
QWidget *widget);
void setColor(const QColor &color) { brushColor = color; }
QColor brushColor;
};
改写mainwindows.cpp 函数,主要是完成如下几个任务创建场景,创建视图,添加图元,加载动画。具体代码如下:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "tagobject.h"
#include <QGraphicsView>
#include <QGraphicsScene>
#include <QAbstractAnimation>
#include<QPropertyAnimation>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
QGraphicsView *graphicsView = new QGraphicsView() ; //新建一个视图
setCentralWidget(graphicsView);
//新建一个场景,并将这个场景可视
QGraphicsScene *_scene = new QGraphicsScene(this); // 新建一个场景
_scene->setItemIndexMethod(QGraphicsScene::NoIndex);
graphicsView->setScene(_scene);
graphicsView->show();
tagObject *tg = new tagObject(); //创建图元对象
tg->setColor(QColor(100,100,250)); // 设置颜色
_scene->addItem(tg); //将图元添加到场景中
//加载动画机制,实现动画
QPropertyAnimation * animation1 = new QPropertyAnimation(tg,"pos");
animation1->setDuration(2000);
animation1->setStartValue(QPoint(0, 0));
animation1->setEndValue(QPoint(300, 300));
animation1->setEasingCurve(QEasingCurve::OutQuad);
animation1->start(QAbstractAnimation::KeepWhenStopped);
}
MainWindow::~MainWindow()
{
delete ui;
}
总结: Qt动画机制使用还是很简单。在项目中,为了实现更好的UI效果,往往会用到它。