QGraphicsView 更改鼠标样式 以及QGraphicsItem悬停时更改鼠标样式

来源:互联网 发布:英特尔proset无线软件 编辑:程序博客网 时间:2024/06/13 11:08

一个编辑区域,用QGraphi参数View写的,可以放大,鼠标按下后可以拖拽查看,这个时候希望鼠标可以是"小手"抓取的样子.QGraphicsView上有一些个QGraphicsItem,希望鼠标悬停在item上时可以变成四向箭头,然后可以拉伸item.

所以重新了QGraphicsView的

void mousePressEvent(QMouseEvent *event);
void mouseMoveEvent(QMouseEvent *event);
void mouseReleaseEvent(QMouseEvent *event);

三个方法,并在其中写了判断,

if (m_bDrag)
{
this->setCursor(Qt::OpenHandCursor);
}

QGraphicsItem重写了

void hoverEnterEvent(QGraphicsSceneHoverEvent *event);
void hoverLeaveEvent(QGraphicsSceneHoverEvent *event);
void hoverMoveEvent(QGraphicsSceneHoverEvent *event);

方法,并且也在其中添加了判断,

if (m_bHover)
{
this->setCursor(Qt::SizeAllCursor);
}

但是在运行的时候并没有按照预想的执行,当QGraphicsView中未添加Item的时候,可以显示"小手"的拖拽光标,也可以进行图标切换,但是当添加过item后,

虽然也执行了view中改变鼠标样式的函数,但是并没有效果,当鼠标悬停在Item上方的时候,鼠标样式发生改变.

分析了一下,this->setCursor(Qt::OpenHandCursor);和this->setCursor(Qt::SizeAllCursor);的this并不是一个对象,this是View对象,而this是item对象,

所以在Item的悬停方法中,我改成这样

void MytItem::hoverMoveEvent(QGraphicsSceneHoverEvent *event)
{
if (m_bHover)
{

// 获取当前item所属于的scene,然后获取scene的Views,因为我只有一个View,所以用下标at(0)获取了view

QGraphicsView * view = this->scene()->views().at(0);

// 然后用view设置鼠标样式
view->setCursor(Qt::SizeAllCursor);
}
QGraphicsItem::hoverMoveEvent(event);
}

问题解决,在查找的时候,发现有一篇博客这样写,但是还未验证

解决方法就是在QGraphicsView子类中使用viewport()->setCursor()而不是直接的setCursor(),这样才能真正改变视觉上的鼠标形状。viewport()函数定义在QAbstractScrollArea类中,QGraphicsView继承自QAbstractScrollArea类,对于更新更新视图内容应该用viewport()->update(),而不是直接用update()。

http://blog.csdn.net/afterward___/article/details/46408355