QGraphicsItem的缩放
来源:互联网 发布:弈乐麻将 游戏网络 编辑:程序博客网 时间:2024/06/02 06:28
QGraphicsItem的缩放
QgarphicsItem是Qt视图体系中的项。QGraphicsItem本身是不支持鼠标拖动来缩放的,本文介绍如何通过更改鼠标事件来修改项的大小。(本文所用Qt版本为Qt4.8)
下文代码实现的功能为:按住shift,再用鼠标拖动,可以改变Box的大小。
定义类Box
class Box:public QGraphicsItem{ Q_DECLARE_TR_FUNCTIONS(Box)public: Box(); ...protected: void mousePressEvent(QGraphicsSceneMouseEvent *event); void mouseMoveEvent(QGraphicsSceneMouseEvent *event); void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);};
Box::Box(){ setFlags(QGraphicsItem::ItemIsSelectable| QGraphicsItem::ItemIsMovable| QGraphicsItem::ItemSendsGeometryChanges| QGraphicsItem::ItemIsFocusable); //接受键盘事件 mBoundingRect = QRectF(0,0,100,100); mBoundingRect.translate(-mBoundingRect.center());}
上面两段代码为Box类的定义及构造函数的实现,最重要的是三个鼠标函数的重载,及在setFlag中使Box可以接受键盘事件。
重载mousePressEvent
void Box::mousePressEvent(QGraphicsSceneMouseEvent *event){ if(event->modifiers()&Qt::ShiftModifier) { resizing = true; //resizing变量在鼠标点击时变为true //在放开时变为false setCursor(Qt::SizeAllCursor);//鼠标样式变为十字 } else QGraphicsItem::mousePressEvent(event);}
重载mouseMoveEvent
void Box::mouseMoveEvent(QGraphicsSceneMouseEvent *event){ if(resizing) { QRectF rect(mBoundingRect); if(event->pos().x()<rect.x()) rect.setBottomLeft(event->pos()); else rect.setBottomRight(event->pos()); mBoundingRect=rect; mBoundingRect.translate(-mBoundingRect.center()); scene()->update(); } else QGraphicsItem::mouseMoveEvent(event);}
在这里,简单的更新Box的左下角和右上角来匹配鼠标位置。更好的做法是分别处理x和y坐标。
重载mouseReleaseEvent
void Box::mouseReleaseEvent(QGraphicsSceneMouseEvent *event){ if(resizing) { resizing = false; setCursor(Qt::ArrowCursor); } else QGraphicsItem::mouseReleaseEvent(event);}
用户在改变大小的过程中放开鼠标,就将resizing改为true,以及将鼠标样式变回箭头。
完整的程序我已上传,请点击这里。
版本信息
1.0 20170921
本作品采用知识共享署名-相同方式共享 3.0 未本地化版本许可协议进行许可。
阅读全文
2 0
- QGraphicsItem的缩放
- QGraphicsItem 的坐标问题
- QGraphicsItem的坐标问题
- 常见的QGraphicsItem
- 自己实现的qgraphicsitem
- QGraphicsItem
- QGraphicsItem
- QGraphicsItem
- QGraphicsItem
- QGraphicsItem
- QGraphicsItem的子类化问题
- 自定义QGraphicsItem的继承顺序
- QT QGraphicsItem飞舞的蝴蝶
- QGraphicsScene管理QGraphicsItem(单击/选择/移动/缩放/删除)
- QGraphicsScene管理QGraphicsItem(单击/选择/移动/缩放/删除)
- Qt中QGraphicsItem/View/Scene的哲学
- 提高QGraphicsItem移动效率的解决方案
- 从 QGraphicsItem 的 hover 说开来
- 【HDU4374】One hundred layer-单调队列优化DP
- tablayout
- 模拟 [bzoj 4582] Diamond Collector
- 遇到多个构造器参数时要考虑用构建器Bulider
- 后缀数组入门练习
- QGraphicsItem的缩放
- 9.20...
- 知识点复习
- Spring AOP 之 通知、连接点、切点、切面
- HDU 4273(计算几何+凸包重心)
- 二叉树的创建与遍历(递归)
- 第四周训练总结(一)
- “挖坑填坑”理解快速排序
- Oracle数据库入门 基础知识day05 火推阳光笔记