Reputation: 104
I want to apply a stylesheet to a particular Qwidget
that I create in the constructor of the parent QWidget
. I don't want to create the QWidget
in the Designer, but I want to create it dynamically.
This is my code
enum {one = 0,
two = 1,
three = 2};
cMainForm::cMainForm(QWidget *parent) : QWidget(parent), ui(new Ui::cMainForm) {
//...
QWidget* widgetTest[3];
widgetTest[one] = new QWidget(this);
widgetTest[one]->setGeometry(100,100,100,100);
widgetTest[one]->show();
widgetTest[one]->raise();
//...
setStyleSheet("QWidget#widgetTest[one]{"
"background-color: red;"
"}"
);
//...
}
And doesn't work.
If I change the styleSheet:
setStyleSheet("QWidget{"
"background-color: red;"
"}"
);
The stylesheet is applied to all the widgets. But I don't want this; I want to apply the stylesheet only to that particular widget.
Also if I don't use an array, it doesn't work.
QWidget* widgetTest;
widgetTest = new QWidget(this);
widgetTest->setGeometry(100,100,100,100);
widgetTest->show();
widgetTest->raise();
//...
setStyleSheet("QWidget#widgetTest{"
"background-color: red;"
"}"
);
I already searched the documentation.
What's the solution?
Upvotes: 2
Views: 550
Reputation: 10047
The selector you're using (#
) refers to the widget objectName
property, not the variable name (the style engine knows nothing about your variables). Give the widget an object name:
widgetTest->setObjectName("widgetTest");
then set the stylesheet:
widgetTest->setStyleSheet("QWidget#widgetTest { background-color: red }");
Upvotes: 4