我想用QLinerGradient刷我的子部件。我使用QtDesigner创建了ui。

但是我不能使用这段代码来刷这个小部件。(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);此外,此代码在独立的QWidget中工作,application.This是它的输出:

但在我的设计中我不能做同样的事情。我可以用styleSheet来做这个
ui.colorBarWidget->setStyleSheet( "background-color: qlineargradient( x1:0 y1:0, x2:0 y2:1, stop:0 blue, stop:1 red )" ); /* works */但是为什么我不能用QPalette做这件事。
提前谢谢。
发布于 2016-04-07 17:36:37
我找到了解决办法。如果在设置调色板后使用:
ui.colorBarWidget->setAutoFillBackground(true);此属性默认为false。所以你应该启用它,然后一切都好。但你也应该考虑尺寸,固定尺寸更好。
发布于 2016-03-31 11:09:54
我不知道ui.colorBarWidget是什么类型的小部件,但它看起来不是一个条目小部件,比如QLineEdit或QComboBox。
因此,您应该使用QPalette::Window角色而不是QPalette::Base。
在Qt文档中,对QPalette::Base role有如下描述
主要用作文本输入小部件的背景色,但也可用于其他绘图--例如组合框的背景、下拉列表和工具栏句柄。通常是白色或另一种浅色。
https://stackoverflow.com/questions/36331496
复制相似问题