Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get variable name of Qt Widget (for use in Stylesheet)?

In my application, a User clicks on any widget of my program (which are at the time; dormant) and picks a color for it.
This color will then be added to a stylesheet for that particular widget.

However, when the program ends and is started again, I would like that particular widget to retain its stylesheet.
I would like to not have to hard code in stylesheets for every widget. In fact, I'd rather not even know which particular widget is having the stylesheet.

What I'd really like to do is have a single style sheet for the application, and code the new color just to the particular widget clicked.

(ie: If the User clicked on a QPushButton and chose a stylesheet of { color: red},
I would like just THAT QPushButton red and none others.
So, if that QPushButton had a variable name of 'Clicky',
to the QApplications stylesheet I would add:
'QPushButton#Clicky { color: red }' )

To do this and not have to hard-code it in for every widget,
I must somehow convert the variable name of my PyQt4 widgets to strings.
How can I do this?

Thanks!

(I've read it can be extremely difficult to get python variable names from their values;
Is there any other form of ID for a widget that can be added to a stylesheet?)


PyQt4
python 2.7.2
Windows 7

like image 538
Anti Earth Avatar asked Jan 24 '12 07:01

Anti Earth


1 Answers

You need to first setObjectName("somename") before an object is named, then objectName() will work, or even better - findChild(), or findChildren()

Example

header:

QButton foo;

class:

foo = new QButton();
foo.setObjectName("MySuperButton");

Then, finally in your QSS..

#MySuperButton { 
     background: black;
}

This also works similarly to CSS with

QButton#MySuperButton {
     background: red;
}

The logic behind why you'd want to set multiple object names similarly (for different objects), or use the granularity of only one type of widget with a specific name is also pretty much the same as CSS.

like image 155
synthesizerpatel Avatar answered Oct 23 '22 18:10

synthesizerpatel