获取 Qt Widget 的变量名称(用于样式表)? [英] Get variable name of Qt Widget (for use in Stylesheet)?

查看:159
本文介绍了获取 Qt Widget 的变量名称(用于样式表)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,用户单击我程序的任何小部件(当时处于休眠状态)并为其选择一种颜色.
然后,此颜色将添加到该特定小部件的样式表中.

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.

(即:如果用户点击了一个 QPushButton 并选择了一个 { color: red} 样式表,
我只想要那个 QPushButton 红色,没有其他.
因此,如果 QPushButton 的变量名称为Clicky",
到我要添加的 QApplications 样式表:
'QPushButton#Clicky { color: red }' )

(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 }' )

要做到这一点,而不必为每个小部件对其进行硬编码,
我必须以某种方式将 PyQt4 小部件的变量名称转换为字符串.
我该怎么做?

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?

谢谢!

(我读过从它们的值中获取 python 变量名是非常困难的;
小部件是否还有其他形式的 ID 可以添加到样式表中?)

(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
蟒蛇 2.7.2
视窗 7

PyQt4
python 2.7.2
Windows 7

推荐答案

你需要在命名对象之前先 setObjectName("somename"),然后 objectName() 会起作用,或者更好——findChild(),或者 findChildren()

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

示例

标题:

QButton foo;

类:

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

然后,终于在你的 QSS..

Then, finally in your QSS..

#MySuperButton { 
     background: black;
}

这也类似于带有

QButton#MySuperButton {
     background: red;
}

为什么要类似地设置多个对象名称(针对不同的对象),或仅使用一种具有特定名称的小部件的粒度的逻辑也与 CSS 几乎相同.

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.

这篇关于获取 Qt Widget 的变量名称(用于样式表)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆