Search code examples
c++qtsizeqgraphicsviewqgraphicsitem

get size of QGraphicsView from QGraphicsItem


Q: How can I get graphicsview width and height from my own graphicsItem that subclass from QGraphicsItem ?


Solution

  • Assuming that there is only one view of your scene:

    #include <QtWidgets>
    
    class SimpleItem : public QGraphicsItem
    {
    public:
        QRectF boundingRect() const
        {
            qreal penWidth = 1;
            return QRectF(-10 - penWidth / 2, -10 - penWidth / 2, 20 + penWidth, 20 + penWidth);
        }
    
        void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
        {
            QGraphicsView *view = scene()->views().first();
            qDebug() << "View width:" << view->width() << "height:" << view->height();
            painter->drawRect(-10, -10, 20, 20);
        }
    };
    
    int main(int argc, char *argv[])
    {
        QApplication app(argc, argv);
        QGraphicsView view;
        QGraphicsScene *scene = new QGraphicsScene;
        scene->addItem(new SimpleItem());
        view.setScene(scene);
        view.show();
        return app.exec();
    }
    

    See QGraphicsItem::scene() and QGraphicsScene::views().