Changing QPalette of widget inside QGraphicsScene not working
-
Hello
I'm trying to change the color of a widget which inherits from QFrame using QPalette. This widget is then used in a QGraphicsScene.
class State : public QFrame { public: State(QString name, QWidget* parent = nullptr) : QFrame{parent} { QVBoxLayout* layout{new QVBoxLayout}; label_->setText(name); layout->addWidget(label_); setLayout(layout); setFrameStyle(QFrame::Box); // Not working at all QPalette palette{QFrame::palette()}; palette.setColor(QPalette::Base, Qt::red); setPalette(palette); } private: QLabel* label_{new QLabel}; };Sadly this doesn't seem to do anything? I've tried changing various ColorRoles (e.g. Window) but the widget still looks the same. I'm currently using Qt 6.3.0.
-
I just realized that it actually does work, but only if I disable my stylesheet.
Is this behavior wanted? Does a stylesheet take precedence over locally set palettes? -
Oh I see thank you.
What's the recommended best practice to "slightly" change a widgets style (e.g. border color) then in case I can't change the applied stylesheet? I really only need some kind of visual cue for two different kind of states.
@vinci QPalette is really unreliable. Some colors cannot be changed by the QPalette and it depends on the style which palette colors influence which part of the widgets. So, I advocate to try to not use QPalette at all.
The best way is actually using stylesheets. You can just set a stylesheet on just this one QFrame object. It can be a small stylesheet changing only this one little thing. Everything else will be inherited from your current global stylesheet.
-
Hi,
I would recommend a look at this excellent article from KDAB about using custom QStyle.