这里我有一个 QComboBox 的子类,它将根据其内容的有效性来更改其文本的颜色。
namespace
{
const QString GOOD = "good";
const QString BAD = "bad";
}
NewDBLabel :: NewDBLabel( DB db, const QString & table ) :
m_db (db)
{
connect (this, SIGNAL (textChanged (const QString &)),
this, SLOT (changed (const QString &)));
setStyleSheet (
"QWidget#" + GOOD + " {color: black;} "
"QWidget#" + BAD + " {color: darkRed;}");
}
void NewDBLabel :: changed (const QString & label)
{
if (m_db .label_exists (m_table, label))
{
qWarning ("exists"); // this is printed correctly
setObjectName (BAD);
emit valid (false);
}
else
{
qWarning ("new"); // this is printed correctly
setObjectName (GOOD);
emit valid (true);
}
}
Run Code Online (Sandbox Code Playgroud)
据我所知,这符合文档: “QWidget#foo”应该匹配objectName为foo的QWidget的子类。
我预计 setObjectName 会导致应用不同的样式规则,但这并没有发生。知道为什么吗?
语法是正确的,但stylesheet不是那么动态。在您的代码中,您setObjectName()设置后stylesheet,因此objectName被更改,但qss没有重新应用。所以尝试使用unpolish/polish小部件。在这种情况下qss将能够检测到新的objectNames和属性。例如:
//in ctor
ui->pushButton->setStyleSheet("QWidget#good {color: green;}"
"QWidget#bad {color: red;} ");
//in handler
if(ui->pushButton->objectName() == "good")
ui->pushButton->setObjectName("bad");
else
ui->pushButton->setObjectName("good");
ui->pushButton->style()->unpolish(ui->pushButton);
ui->pushButton->style()->polish(ui->pushButton);
Run Code Online (Sandbox Code Playgroud)
编辑
在我的答案的第一个版本中,我建议重新申请stylesheet,但我删除了这个,因为最好最快的方法是unpolish/polish小部件。此外,setStyleSheet()调用polish()并再次解析整个字符串,因此这只是完全不必要的步骤,这只会降低性能。