QgarphicsItem是Qt視圖體系中的項(xiàng)。QGraphicsItem本身是不支持鼠標(biāo)拖動(dòng)來縮放的,本文介紹如何通過更改鼠標(biāo)事件來修改項(xiàng)的大小。(本文所用Qt版本為Qt4.8)
下文代碼實(shí)現(xiàn)的功能為:按住shift,再用鼠標(biāo)拖動(dòng),可以改變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類的定義及構(gòu)造函數(shù)的實(shí)現(xiàn),最重要的是三個(gè)鼠標(biāo)函數(shù)的重載,及在setFlag中使Box可以接受鍵盤事件。
void Box::mousePressEvent(QGraphicsSceneMouseEvent *event) { if(event->modifiers()&Qt::ShiftModifier) { resizing = true; //resizing變量在鼠標(biāo)點(diǎn)擊時(shí)變?yōu)閠rue //在放開時(shí)變?yōu)閒alse setCursor(Qt::SizeAllCursor);//鼠標(biāo)樣式變?yōu)槭? } 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的左下角和右上角來匹配鼠標(biāo)位置。更好的做法是分別處理x和y坐標(biāo)。
void Box::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { if(resizing) { resizing = false; setCursor(Qt::ArrowCursor); } else QGraphicsItem::mouseReleaseEvent(event); }
用戶在改變大小的過程中放開鼠標(biāo),就將resizing改為true,以及將鼠標(biāo)樣式變回箭頭。
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問題請及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com
本文如未解决您的问题请添加抖音号:51dongshi(抖音搜索懂视),直接咨询即可。