QGraphicsItem使用注意点

我在用qt编写缩放图片的功能的时候(见https://blog.csdn.net/weixin_43935474/article/details/89327314)我是在主界面上放置了一个QGraphicsView,然后里面放了QGraphicsScene,然后自己重写了QGraphicsItem类并放到QGraphicsScene中,从而显示图片并进行缩放操作。其中有2个问题困扰了好久,现在终于解决了:
一、如何在外部获取qgraphicview中qgraphicitem的消息?
具体操作:
1.重写QGraphicsItem类时,先继承Qobject,再继承qgraphicview,否则会报错,如下:(我重写的QGraphicsItem名为ImageWidget )

class ImageWidget :public QObject, public QGraphicsItem
{
    Q_OBJECT
    ······

2.添加signales

signals:
    void    showPos(QPointF pointf, QColor qColor,qreal qrScale);

3.在主界面添加信号响应函数并建立连接:

QObject::connect(m_Image,&ImageWidget::showPos,this,&MainW::showMousePos);//该行代码写在主界面类的构造函数中
void MainW::showMousePos(QPointF point, QColor qColor, qreal qrScale)
{
	//TODO:
}

二、QGraphicsItem类内部获取鼠标移动的消息
一开始用:

void ImageWidget::mouseMoveEvent(QGraphicsSceneMouseEvent *event)

后来发现在用户没有点击鼠标的情况下无法触发该函数。
然后改用:

void ImageWidget::hoverMoveEvent(QGraphicsSceneHoverEvent *event)

就可以了,并且要在主界面函数中添加如下代码:

m_Image->setAcceptHoverEvents(true);//m_Image是ImageWidget对象
m_graphicsScene->addItem(m_Image);//m_graphicsScene是QGraphicsScene对象
m_GraphicView->setScene(m_graphicsScene);//m_GraphicView是QGraphicsView对象
m_GraphicView->setMouseTracking(true);

猜你喜欢

转载自blog.csdn.net/weixin_43935474/article/details/89917667