Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 484
fbg13 Avatar asked Dec 10 '25 03:12

fbg13


1 Answers

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");
like image 144
eyllanesc Avatar answered Dec 12 '25 00:12

eyllanesc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!