1

i am a newbie to Qt.i am handling canvas widgets through QGraphicsScene class.But i cant change the default white background of the widget.Here is the code.i have tried to use the QBrush to set the background.But it did not work.it remains white.what is the problem in the following code?

int main(int argc, char **argv){

    QApplication a(argc, argv);


    QGraphicsScene canvas;
    canvas.addText("Hello World");
    QColor *color=new QColor(0x70,0x80,0x50,255);
    QBrush *brush=new QBrush();
    brush->setColor(*color);
    canvas.setBackgroundBrush(*brush);

    QGraphicsView view(&canvas);
    view.show();




    return a.exec();


}
manmatha.roy
  • 577
  • 1
  • 9
  • 22
  • 1
    This doesn't answer your question, but just FYI, your code is leaking memory. Don't use the new operator to allocate your QColor and QBrush objects, instead declare them as stack objects (the same way you did with your QApplication and QGraphicsScene objects). setColor() and setBackgroundBrush() will make copies of them anyway, so there is no benefit to allocating them with new. – Jeremy Friesner Mar 29 '13 at 04:50

2 Answers2

6

Try passing the color into the brush constructor instead of afterwards

QBrush brush(QColor(0x70, 0x80, 0x50, 255));
canvas.setBackgroundBrush(brush);

Which will set the brush style to Qt::SolidPattern. The default brush constructor sets the style to Qt::NoBrush. See http://qt-project.org/doc/qt-4.8/qbrush.html#QBrush

Kevin Tonon
  • 965
  • 10
  • 18
  • it worked well.Can you just say that how can I change the Text Color on the canvas(QGraphicsScene::addText) – manmatha.roy Mar 29 '13 at 14:37
  • `QGraphicsScene::addSimpleText` returns a pointer to a newly created `QGraphicsSimpleTextItem`. You can then change the brush for that text time. For example, `canvas.addSimpleText("Hello World")->setBrush(Qt::red);` – Kevin Tonon Mar 29 '13 at 15:14
-1
view.setStyleSheet("background-color: black;");