0

My work Environment :Qt 5.8 MSVC2015 64bit, QT GraphicsView, QGraphicsRectItem, Windows 7 64 bit.

Issues : When I zoom in & zoom out on GraphicsView, I call GraphicsView scale method. But When I add QGraphicsRectItem to scene it failed to call its paint method.

my class hierachy :

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

Code :

//////*****Draw Rect in 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(); 
}

Here is git code

I spend days & hours but still not able to find out why it QGraphicsRectItem failed to print, when scale method get called. Any suggestion is highly appreciated ?

Sandip
  • 51
  • 11
  • The line "mySquare _square = new mySquare(0,blankImage);" will not compile. Please edit your question to show the real code. – G.M. Jun 20 '17 at 11:55
  • Updated git code url : https://github.com/SandyWare/ImageRender – Sandip Jun 20 '17 at 12:58
  • Pay attention to extend from `QObject` and `QGraphicsRectItem` there is a class for this special purpose [QGraphicsObject](http://doc.qt.io/qt-5.9/qgraphicsobject.html) – Elia Jun 20 '17 at 13:38
  • @Elia : Thanks, I have changed class mySquare : public QGraphicsObject – Sandip Jun 21 '17 at 14:21

1 Answers1

0

thanks for all helps. I found solution by overriding QGraphicsView scale method. changes : class mySquare : public 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);
}
Sandip
  • 51
  • 11