问题
I am looking to change the background color of a QToolButton. I want the shape of the button persevered along with the border. Only the background needs to change. I have tried working with the style sheet and all I get is a small section on the left and right margins with the color change.
I have been attempting to utilize this code snippet:
class ColorButton : public QToolButton
{
Q_OBJECT
public:
explicit ColorButton(QWidget *parent = nullptr) : QToolButton(parent) {}
protected:
virtual void paintEvent(QPaintEvent *) override
{
QStylePainter p(this);
QStyleOptionToolButton opt;
initStyleOption(&opt);
p.drawComplexControl(QStyle::CC_ToolButton, opt);
p.setBrush(QColor(255,0,0,100));
p.setPen(Qt::NoPen);
p.drawRect(4,4,width()-8,height()-8);
}
};
However, all I get is a red rectangle colored red that is drawn on top of the text. This mostly works however, the text now was a red tint to it.
Basically, all I need and want is to be able to change the background color. If I use the provided snippet, I would need to figure out how I can force draw the text as the foreground.
Or if there is a better way then please let me know!
Thank you.
Edit:
I am running Qt 5.9 on the latest version of Linux Mint (as of this writing)
Edit 2:
I should also note that I have attempted using the QPalette to change the color. This did not work. Sample code posted:
p_deactiveColor.setBrush(QPalette::Base, QColor(Qt::red));
p_deactiveColor.setBrush(QPalette::Button, QColor(Qt::red));
p_deactiveColor.setBrush(QPalette::Window, QColor(Qt::red));
p_deactiveColor.setBrush(QPalette::WindowText, QColor(Qt::red));
p_activeColor.setBrush(QPalette::Base, QColor(Qt::green));
p_activeColor.setBrush(QPalette::Button, QColor(Qt::green));
ui->cupExtendButton->setPalette(p_deactiveColor);
Please note, I tried various combinations of the p_deactiveColor.setBrush
function. I posted the various settings that I edited here. Non of the combinations worked
来源:https://stackoverflow.com/questions/57045926/how-to-change-the-background-color-of-qtoolbutton