fbg13 fbg13 - 1 month ago 17
C++ Question

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");
QString style( File.readAll() );

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;



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?

Answer Source

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;