QT案例解析(1): Animated Tiles Example

演示效果

在这里插入图片描述

步骤概述

  1. 继承QGraphicsPixmapItem 实现显示图片
  2. 继承QGraphicsWidget 实现按钮
  3. 继承QGraphicsView 实现视图
  4. 实现功能
    图像不同状态的动画切换。

涉及知识点

图形视图框架 (QGraphicsScene(场景)),QGraphicsView(视图)),QGraphicsItem(图形项))
动画框架 (QAbstractAnimation(基类))
状态机框架 (QStateMachine(状态机) QState(状态))
信号与槽 (Signals & Slots)
2D绘图 (paint)

代码解析

一、继承QGraphicsPixmapItem

实现图片显示。
只是修改缓存模式。

class Pixmap : public QObject, public QGraphicsPixmapItem
{
   
    Q_OBJECT
    Q_PROPERTY(QPointF pos READ pos WRITE setPos)
public:
    Pixmap(const QPixmap &pix)
        : QObject(), QGraphicsPixmapItem(pix)
    {
   
    	//开启缓存模式(高质量显示)
        setCacheMode(DeviceCoordinateCache);
    }
};
二、继承QGraphicsWidget

实现按钮功能。
重写 paint 实现 悬停和点击 的效果 相当于设置样式

class Button : public QGraphicsWidget
{
   
    Q_OBJECT
public:
    Button(const QPixmap &pixmap, QGraphicsItem *parent = 0)
        : QGraphicsWidget(parent), _pix(pixmap)
    {
   
    	//使能悬停功能
        setAcceptHoverEvents(true);
        //开启缓存模式(高质量显示)
        setCacheMode(DeviceCoordinateCache);
    }
	//设置按钮理想大小(默认大小)
    QRectF boundingRect() const Q_DECL_OVERRIDE
    {
   
        return QRectF(-65, -65, 130, 130);
    }
	//返回按钮区域
    QPainterPath shape() const Q_DECL_OVERRIDE
    {
   
        QPainterPath path;
        //注意这里是椭圆了
        path.addEllipse(boundingRect()); 
        return path;
    }
	
    void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *) Q_DECL_OVERRIDE
    {
   
    	//判断下陷状态 (pressed)
        bool down = option->state & QStyle::State_Sunken;
        QRectF r = boundingRect();
        //线性渐变
        QLinearGradient grad(r.topLeft(), r.bottomRight());
        grad.setColorAt(down ? 1 : 0, option->state & QStyle::State_MouseOver ? Qt::white : Qt::lightGray);
        grad.setColorAt(down ? 0 : 1, Qt::darkGray);
        painter->setPen(Qt::darkGray);
        painter->setBrush(grad);
        //画外圈
        painter->drawEllipse(r);
        grad.setColorAt(down ? 1 : 0, Qt::darkGray);
        grad.setColorAt(down ? 0 : 1, Qt
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值