FengF2017通过本文主要向大家介绍了qt,qt4等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com
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 未本地化版本许可协议进行许可。