[英]QPalette does not work on sub QWidget
I want to brush my sub widget with QLinerGradient. 我想用QLinerGradient刷我的子小部件。 I have created ui by using QtDesigner. 我已经使用QtDesigner创建了ui。
But I can not brush this widget by using this code.(ui.colorBarWidget is normal QWidget was created by QtDesigner.) 但是我无法使用此代码刷此小部件。(ui.colorBarWidget是正常的QWidget是由QtDesigner创建的。)
QPalette palette;
QLinearGradient gradient(ui.colorBarWidget->rect().topLeft(),ui.colorBarWidget->rect().topRight());
gradient.setColorAt(0, Qt::blue);
gradient.setColorAt(0.2, Qt::green);
gradient.setColorAt(0.4, Qt::red);
gradient.setColorAt(0.6, Qt::yellow);
gradient.setColorAt(1, Qt::cyan);
palette.setBrush(QPalette::Base, gradient);
ui.colorBarWidget->setPalette(palette);
In addition this code works in stand alone QWidget application.This is its output: 此外,此代码可在独立的QWidget应用程序中工作,其输出为:
But I can not do same thing in my design. 但是我不能在设计中做同样的事情。 I can do this with styleSheet 我可以用styleSheet做到这一点
ui.colorBarWidget->setStyleSheet( "background-color: qlineargradient( x1:0 y1:0, x2:0 y2:1, stop:0 blue, stop:1 red )" ); /* works */
but why I can not do this with QPalette. 但是为什么我不能用QPalette做到这一点。
Thanks in advance. 提前致谢。
I don't know what kind of widget is ui.colorBarWidget
, but it looks it's not an entry widget, like QLineEdit
or QComboBox
. 我不知道ui.colorBarWidget
是ui.colorBarWidget
小部件,但它看起来不是输入部件,例如QLineEdit
或QComboBox
。
So, you should use a QPalette::Window
role instead of QPalette::Base
. 因此,您应该使用QPalette::Window
角色而不是QPalette::Base
。
In the Qt documentation, there is a following description for the QPalette::Base role
: 在Qt文档中,对QPalette::Base role
有以下描述:
Used mostly as the background color for text entry widgets, but can also be used for other painting - such as the background of combobox drop down lists and toolbar handles. 主要用作文本输入小部件的背景颜色,但也可以用于其他绘画-例如组合框下拉列表和工具栏手柄的背景。 It is usually white or another light color. 通常为白色或其他浅色。
I found the solution. 我找到了解决方案。 If you use after setting palette: 如果在设置调色板后使用:
ui.colorBarWidget->setAutoFillBackground(true);
This property is default false. 此属性默认为false。 So you should enable it then everything is fine. 因此,您应该启用它,然后一切都很好。 But also you should consider the size, fixed size better for this. 但是您也应该考虑大小,为此,固定大小更好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.