3
votes

I want to brush my sub widget with QLinerGradient. I have created ui by using QtDesigner.

enter image description here

But I can not brush this widget by using this code.(ui.colorBarWidget is normal QWidget was created by 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:

enter image description here

But I can not do same thing in my design. I can do this with 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.

Thanks in advance.

2

2 Answers

1
votes

I found the solution. If you use after setting palette:

ui.colorBarWidget->setAutoFillBackground(true);

This property is default false. So you should enable it then everything is fine. But also you should consider the size, fixed size better for this.

0
votes

I don't know what kind of widget is ui.colorBarWidget, but it looks it's not an entry widget, like QLineEdit or QComboBox.

So, you should use a QPalette::Window role instead of QPalette::Base.

In the Qt documentation, there is a following description for the 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.