tri*_*leM 3 qt qgraphicsview qgraphicsitem qgraphicsscene custom-widgets
我有一个QGraphicsView更大的QGraphicsScene可以拖动的。在QGraphicsScene我有一个子类QGraphicsItem( TestItem) 中,它显示QGraphicsPixmapItem,它可以具有随机形状。(我不QGraphicsPixmapItem直接使用,因为将来要实现额外的功能)
我希望这个项目是可移动的,但前提是用户在该项目的形状内按下。如果在形状之外,但仍在 内部boundingRectangle,我希望拖动其后面的场景。这是因为boundingRectangle可能比形状大得多并且用户看不到它,所以尝试将场景拖动到 附近Pixmap并且它不起作用会很奇怪。
这是我的子类项目:
TestItem::TestItem(QPointF position, QPixmap testImage, double width,
double length, QGraphicsItem * parent):
QGraphicsItem(parent),
m_boundingRect(QRectF(0,0,5, 5)),
m_dragValid(false),
m_path(QPainterPath()),
mp_image(new QGraphicsPixmapItem(this))
{
setBoundingRect(QRectF(0,0,width,length));
setPos(position - boundingRect().center());
setFlag(QGraphicsItem::ItemIsMovable);
mp_image->setPixmap(testImage.scaled(width, length));
m_path = mp_image->shape();
}
QPainterPath TestItem::shape()
{
return m_path;
}
QRectF TestItem::boundingRect() const
{
return m_boundingRect;
}
void TestItem::setBoundingRect(QRectF newRect)
{
prepareGeometryChange();
m_boundingRect = newRect;
}
Run Code Online (Sandbox Code Playgroud)
我尝试过像这样覆盖鼠标事件,但它给我带来的只是在形状外部但在边界矩形内部时根本没有任何功能
void TestItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
if(shape().contains(event->pos()))
{
QGraphicsItem::mousePressEvent(event);
m_dragValid = true;
}
}
void TestItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
if(m_dragValid)
QGraphicsItem::mouseMoveEvent(event);
}
void TestItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
if(m_dragValid)
QGraphicsItem::mouseReleaseEvent(event);
m_dragValid = false;
}
Run Code Online (Sandbox Code Playgroud)
这当然是有道理的,但我不知道如何实现场景的拖动,因为场景本身将鼠标事件发送到图形项。
(我的QGraphicsView设置为DragMode QGraphicsView::ScrollHandDrag)
有人有想法吗?
我想到了。我只需要添加一个event->ignore();到我的鼠标事件。
void TestItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
if(shape().contains(event->pos()))
{
QGraphicsItem::mousePressEvent(event);
m_dragValid = true;
}
else
event->ignore();
}
void TestItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
if(m_dragValid)
QGraphicsItem::mouseMoveEvent(event);
else
event->ignore();
}
void TestItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
if(m_dragValid)
QGraphicsItem::mouseReleaseEvent(event);
else
event->ignore();
m_dragValid = false;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3725 次 |
| 最近记录: |