Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

QPainter in QGraphicsView::drawBackground() does not paint anything?



  • Hey,
    I have a QGraphicsView class and implemented the funtion drawBackground:

    void GraphWidget::drawBackground(QPainter *painter, const QRectF &rect)
    {
        Q_UNUSED(rect);
    
    
        QRectF sceneRect = this->sceneRect();
    
        QLinearGradient sceneGradient(sceneRect.topLeft(), sceneRect.bottomRight());
        sceneGradient.setColorAt(0, Qt::white);
        sceneGradient.setColorAt(1, Qt::black);
        painter->fillRect(sceneRect, sceneGradient);
        painter->setBrush(Qt::NoBrush);
        painter->drawRect(sceneRect);
    }
    

    Unfortunately something is missing, but what?
    (I am sure, the answer will be just a single line or something like that, I just took it from one of the examples and so far can't find the missing part)
    Thanks for answers


  • Moderators

    Do you have a scene set? If not QGraphicsView will call the default paintEvent of the scroll view and your method won't be called.



  • @Chris-Kawa
    Yes, in the constructor:

        QGraphicsScene *scene = new QGraphicsScene(this);
        scene->setItemIndexMethod(QGraphicsScene::NoIndex);
        scene->setSceneRect(-200, -200, 400, 400);
        setScene(scene);
        setCacheMode( CacheBackground );
        setViewportUpdateMode(BoundingRectViewportUpdate);
        setRenderHint((QPainter::Antialiasing));
        setTransformationAnchor(AnchorUnderMouse);
        scale(qreal(10-0), qreal(10.0));
    

  • Moderators

    Your sample works for me:
    graphicsview

    The problem must be elsewhere in your code.



  • @Chris-Kawa
    Found it!
    As I saw now, I also implemented the paintEvent.
    So, just had to delete it.
    Thanks


Log in to reply