QGraphicsView Scale 和 QGraphicsRectItem paint 调用失败



我的工作环境:Qt 5.8 MSVC2015 64位,QT GraphicsView,QGraphicsRectItem,Windows 7 64位。

问题:当我放大和缩小GraphicsView时,我称之为GraphicsView缩放方法。但是当我将QGraphicsRectItem添加到场景中时,它无法调用其绘制方法。

我的班级层次结构:

  class GraphicsView : public QGraphicsView
  class mySquare : public QObject, public QGraphicsRectItem
  class Scene : public QGraphicsScene 

法典:

////

//*****在 QGraphicsRectItem 中绘制矩形 *****//

void mySquare::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
      QRectF rect(0,0,_width,_height);
      painter->drawRect(rect);
}
  void GraphicsView::wheelEvent(QWheelEvent * event)
{
    int angle = event->angleDelta().y(); // angle will tell you zoom in or out.
    double scaleFactor = 1.15; //How fast we zoom
    setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
    if (angle > 0)
    {
        qDebug()<<"Zoom in";
        scale(scaleFactor, scaleFactor);
    }
    else
    {
        qDebug()<<"Zoom out";
        scale(1.0 / scaleFactor, 1.0 / scaleFactor);
    }
        mySquare  _square = new mySquare(0,blankImage);
       _square->setPos(QPointF(0, 0));
       //add square to scene. 
 //Bug!!! Why after scale function call, _square failed to draw rect in paint method.
        _scene->addItem(_square);
        _square->update(); 
}

这是 git 代码

我花了几天和几小时,但仍然无法找出为什么它QGraphicsRectItem无法打印,当缩放方法被调用时。任何建议都非常感谢 ?

感谢所有的帮助。我通过覆盖QGraphicsView规模方法找到了解决方案。变化: 类 mySquare : 公共 QGraphicsObject

void GraphicsView::scale(qreal scaleFactor)
{
    QRectF r(0, 0, 1, 1); // A reference
    qreal factor = transform().scale(scaleFactor, scaleFactor).mapRect(r).width(); // absolute zoom factor
    ( (rFactor > 0  )
    {
            qDebug()<<"Zoom in";
    }
    else 
    {
            qDebug()<<"Zoom out";
        }
        mySquare  _square = new mySquare(0,blankImage);
       _square->setPos(QPointF(0, 0));
        _scene->addItem(_square);
        _square->update(); 
    }
    QGraphicsView::scale(scaleFactor, scaleFactor);
}

最新更新