Search code examples
c++qtqtstylesheets

How to use QGraphicsScene::setStyle()?


I am using QGraphicsProxyWidget to embed QWidgets inside a QGraphicsScene. The problem comes with the style with which these widgets are drawed. From the documentation:

A top-level item's style defaults to QGraphicsScene::style. A top-level widget's style defaults to QApplication::style

So, I have to set the style to QGraphicsScene. Right now, I am using QWidget::setStyleSheet to set custom styles based on CSS (QSS).

My question is: how can I use QGraphicsScene::setStyle, which requires an instance of QStyle, since I haven't got one? Can somebody post an example using it and setting a stylesheet-enabled style?

I have already tried QStyleFactory::create, but there is no way to create an instance of QStyleSheetStyle.


Solution

  • Since you haven't got an instance of QStyle, the default style used for a QGraphicsScene is QApplication::style(), as it is stated in the documentation.

    The scene's style defaults to QApplication::style(), and serves as the default for all QGraphicsWidget items in the scene.

    The second part of this sentence implies that you can customize your widgets inside a scene (like you are doing right now with QWidget::setStyleSheet). You can assign a style sheet to a widget before adding it into the scene, it will keep its style after being added.

    But it is not possible for a QGraphicsScene, since it has not such a function. Their style should be defined by using a QPalette and set via QApplication::setPalette. Remember that QGraphicsScene also has functions like setBackgroundBrush and setForegroundBrush.

    QPalette pal;
    pal.setColor(QPalette::Base, QColor(255, 0, 0));
    
    QApplication::setPalette(pal);
    
    QGraphicsScene* scene = new QGraphicsScene(400,400,400,400);
    scene->setPalette(pal);
    
    QGraphicsView* view = new QGraphicsView(scene);
    view->show();