Home > front end >  How to change background color in QGraphicsScene?
How to change background color in QGraphicsScene?

Time:02-20

I want to give background color in my QGraphicsScene. For that, I have override drawBackground() method, and tried to set color but it is not working. Background color is not changing.
Here is my drawBackground() method.

Widget.h

QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE

class Widget : public QGraphicsView
{
    Q_OBJECT

public:
    Widget(QWidget *parent = nullptr);
    ~Widget();
protected:
    void drawBackground(QPainter *painter, const QRectF &rect);    
};      
     

Widget.cpp

    Widget::Widget(QWidget *parent)
        : QGraphicsView(parent)
        , ui(new Ui::Widget)
    {
        ui->setupUi(this);
        scene = new QGraphicsScene(this);
    
        view = new QGraphicsView(this);
        view->setScene(scene);
        view->setDragMode(QGraphicsView::RubberBandDrag);
        ui->verticalLayout_2->addWidget(view);
    }
    
   void Widget::drawBackground(QPainter *painter, const QRectF &rect)
   {
       painter->save();
       painter->setBrush(QBrush(Qt::yellow));
       painter->restore();
   }
     
  

Can anyone help me ?

CodePudding user response:

Your code has a number of problems or, at least, inconsistencies. Firstly your Widget class makes use of both inheritance and composition with regard to QGraphicsView in that it derived from QGraphicsView and has a QGraphicsView member. That may be what you want but it seems unlikely.

Firstly, you say...

I want to set background for the ui->verticalLayout_2. So my background should be yellow.

As per my comment, that can be easily done by simply using QGraphicsView::setBackgroundBrush...

view->setBackgroundBrush(Qt::yellow);

The other issue is with your override of drawBackground in the Widget class. Currently you have...

void Widget::drawBackground(QPainter *painter, const QRectF &rect)
{
    painter->save();
    painter->setBrush(QBrush(Qt::yellow));
    painter->restore();
}

But all that does is save the painter's state, set its brush to a solid yellow colour and then restore the state of the painter. It's essentially a noop in that it doesn't actually draw anything. If you really want to override the drawBackground member in this way then try something like...

void Widget::drawBackground(QPainter *painter, const QRectF &rect)
{
    painter->save();
    painter->setPen(Qt::NoPen);
    painter->setBrush(QBrush(Qt::yellow));
    painter->drawRect(rect);
    painter->restore();
}

[As an aside, when overriding a virtual member in a derived class always use the override specifier.]

  • Related