fbg13
fbg13

Reputation: 151

Qt apply style from external stylesheet to a programmatically added widget

I'm loading an external stylesheet to my application (in main.cpp) like this:

QApplication a(argc, argv);
QFile File(":/resources/stylesheet.qss");
File.open(QIODevice::ReadOnly);
QString style( File.readAll() );
a.setStyleSheet(style);

In that style sheet I tried targeting a widget that I create in mainwindow.cpp, the widget is added to a layout created in the same file and the layout is set to a widget created with the designer.

QListWidget *songList = new QListWidget;
QVBoxLayout *vBoxLayout = new QVBoxLayout;

vBoxLayout->addWidget(songList);
ui->midWidgetCenter->setLayout(vBoxLayout);

stylesheet.qss

QListWidget#songList {
    background: red;
}

Omitting the widget name applies the style.

Is it possible to apply the style from an external style sheet to elements created programmatically?

Upvotes: 3

Views: 921

Answers (1)

eyllanesc
eyllanesc

Reputation: 244291

When you use the SomeWidget#SomeName command, qt uses the objectName to apply the style. If you use Qt Designer, set this property to the name of the attribute. But if we create the widget, we must establish that property, in your case the solution is:

QListWidget *songList = new QListWidget;
songList->setObjectName("songList");

Upvotes: 4

Related Questions