从QGraphicsItem获取QGraphicsView的大小

时间:2014-05-15 20:14:48

标签: c++ qt size qgraphicsview qgraphicsitem

:如何从我graphicsview的{​​{1}}子类中获取width heightgraphicsItem?< / p>

1 个答案:

答案 0 :(得分:3)

假设您的场景只有一个视图:

#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();
}

请参阅QGraphicsItem::scene()QGraphicsScene::views()