c++qtqt5qgroupbox

Change title color of QGroupBox only on parent


I have 2 QGroupBoxes and one of them is a child of the other. I want to change the color of the parent's title without changing the color on the child. I tried the following according to qt documentation: https://doc.qt.io/qt-5/stylesheet-examples.html
My code:
mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QGroupBox>

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();


private:
    Ui::MainWindow *ui;
    QGroupBox *r1;
    QGroupBox *r2;
};
#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    r1 = new QGroupBox("test",this);
    r1->setGeometry(10,10,100,100);
    r1->setStyleSheet("QGroupBox::title#r1{color:red}");
    r1->show();
    r2 = new QGroupBox("test",r1);
    r2->setGeometry(10,10,80,80);
    r2->show();
}

MainWindow::~MainWindow()
{
    delete ui;
}

It doesn't work for me. The title does not change color.
If I do the same just by creating the QGroupBox in the designer it works. Help me figure out what I'm doing wrong?


Solution

  • The QSS slightly differs from CSS. Qt just do not know what is r1 in your case. To achieve your desired effect you can:

    1. setObjectName() on the object you want to customize and then refer via this name. Therefore only that one element will have distinct color.
    r1 = new QGroupBox("test",this);
    r1->setGeometry(10,10,100,100);
    r1->setObjectName("r1");
    r1->setStyleSheet("QGroupBox#r1 {color: red}");
    r1->show();
    r2 = new QGroupBox("test",r1);
    r2->setGeometry(10,10,80,80);
    r2->show();
    
    1. Use > selector to match parent - child relationship. In this case all QGroupBox that are direct children of QMainWindow will be red colored.
    r1 = new QGroupBox("test",this);
    r1->setGeometry(10,10,100,100);
    r1->setStyleSheet("QMainWindow > QGroupBox {color: red}");
    r1->show();
    r2 = new QGroupBox("test",r1);
    r2->setGeometry(10,10,80,80);
    r2->show();
    
    1. Use title property value - however, I would strongly not recommend that approach.
    r1 = new QGroupBox("test",this);
    r1->setGeometry(10,10,100,100);
    r1->setStyleSheet("QGroupBox[title='test'] {color: red}");
    r1->show();
    r2 = new QGroupBox("test",r1);
    r2->setGeometry(10,10,80,80);
    r2->show();
    

    More about syntax can be found here: https://doc.qt.io/Qt-5/stylesheet-syntax.html