Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 968
FlKo Avatar asked Oct 22 '17 18:10

FlKo


People also ask

How do I create a styleSheet in Qt?

Styles sheets are textual specifications that can be set on the whole application using QApplication::setStyleSheet() or on a specific widget (and its children) using QWidget::setStyleSheet(). If several style sheets are set at different levels, Qt derives the effective style sheet from all of those that are set.

How do I make the background transparent in Qt?

ui->graphicsView->setBackground( Qt::GlobalColor::transparent );

What is .ui file in Qt?

ui file is used to create a ui_calculatorform. h file that can be used by any file listed in the SOURCES declaration. Note: You can use Qt Creator to create the Calculator Form project. It automatically generates the main.


1 Answers

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.

like image 84
SteakOverflow Avatar answered Sep 20 '22 10:09

SteakOverflow