qgarphicsitem是qt视图体系中的项。qgraphicsitem本身是不支持鼠标拖动来缩放的,本文介绍如何通过更改鼠标事件来修改项的大小。(本文所用qt版本为qt4.8)
下文代码实现的功能为:按住shift,再用鼠标拖动,可以改变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可以接受键盘事件。
void Box::mousePressEvent(QGraphicsSceneMouseEvent *event)
{ if(event->modifiers()&Qt::ShiftModifier)
{
resizing = true; //resizing变量在鼠标点击时变为true //在放开时变为false
setCursor(Qt::SizeAllCursor);//鼠标样式变为十字
} else
QGraphicsItem::mousePressEvent(event);
}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坐标。
void Box::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{ if(resizing)
{
resizing = false;
setCursor(Qt::ArrowCursor);
} else
QGraphicsItem::mouseReleaseEvent(event);
}用户在改变大小的过程中放开鼠标,就将resizing改为true,以及将鼠标样式变回箭头。
以上就是QGraphicsItem的缩放的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号