FlKo
FlKo

Reputation: 845

Qt Style Sheets - Not Applied Background Properties

I'm trying to create a custom widget (itself containing some child widgets) in Qt Creator with Qt Designer.

In the designer I set the styleSheet property for the derived object ControlBar to the following values:

QWidget{
    font-family: "Segoe UI";
    font-size: 9;
}
QWidget#ControlBar{
    background-color: #3a3a3a;
    border-width: 5px;
    border-radius: 4px;
    border-style: solid;
    border-color: #ffffff;
}

Everything looks fine now in designer as well as in the preview mode (Shift+Alt+R).

My intention now is to create an instance of ControlBar at runtime and assign it to the main vertical layout of a MainWindow instance:

MainWindow::MainWindow(QWidget *parent)
:   QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    ControlBar *controlBar = new ControlBar;
    ui->verticalLayout->insertWidget(0, controlBar);
}

Albeit the styling works as expected for every single sub-widget of ControlBar, the given background color (the background-color property of ControlBar's styleSheet in particular) is not applied to the control bar, as well as all the other background-related properties. Instead, the background color and styling of MainWindowis used, whereas all the sub-widget-related styling is working as expected.

How can I get rid of this behaviour and make ControlBarhave it's intended background color?

Upvotes: 6

Views: 2723

Answers (1)

SteakOverflow
SteakOverflow

Reputation: 2033

QWidget#ControlBarrefers to any widget with the object name "ControlBar".

  1. Your widget does not have that object name.
  2. For some reason this does not seem to work when the object name is the same as the class name, except for when the object is the root object.

Hence it it works in the designer and preview, but not as a child of something else.

To solve this, use

ControlBar{
    background-color: #3a3a3a;
}

instead and make sure to inherit ControlBar from QFrame and not form QWidget. If for some reason you cannot, you have to override the paintEvent. See this answer for the exact code.

Upvotes: 7

Related Questions