Showing custom QWidget based on pseudo-state of a stylesheet

I have a custom QWidget (actually obtained from QAbstractButton ) for which I have to implement my own paintEvent . How to use the information in the style sheet?

For example, suppose someone defines the following stylesheet that applies (directly or through inheritance) to my custom class:

 QAbstractButton { font-weight: bold; background-color: red } QAbstractButton:checked { background-color: blue } 

In my paintEvent method, how can I get the correct background color for the displayed state?

 void MyButton::paintEvent(QPaintEvent */*event*/) { ensurePolished(); // Don't think this is necessary... qDebug() << Q_FUNC_INFO << isChecked(); // This is showing the right value QStylePainter painter(this); painter.fillRect(rect(), painter.background()); // always red, even if checked } 

I assume that I need something like:

 if (isChecked()) { // painter.fillRect(rect(), ???); // // style()->drawPrimitive(???, ...); // // QStyleOptionButton opt; // opt.initFrom(this); // QBrush bg_brush = opt.??? // painter.fillRect(rect(), bg_brush); // // ??? } else { painter.fillRect(rect(), painter.background()); } 

How to get a brush for the background of the checked state that Qt allowed from stylesheets?

+6
source share
1 answer

I could never find out how to get the allowed color (and complementary) information, but I was able to get around it by painting sub-elements of other widgets in mine. This is not quite what I tried to do, and may not work in other cases (if your widget cannot be made up by messing up things that Qt knows how to draw).

 void MyButton::paintEvent(QPaintEvent */*event*/) { QStylePainter painter(this); QStyleOptionButton opt; opt.initFrom(this); opt.state |= isChecked() ? QStyle::State_On : QStyle::State_Off; opt.text = text(); painter.drawPrimitive(QStyle::PE_Widget, opt); QStyleOptionButton label_opt = opt; label_opt.rect = style()->subElementRect(QStyle::SE_CheckBoxContents, &opt, this); painter.drawControl(QStyle::CE_CheckBoxLabel, label_opt); // ... etc. } 

I still think there should be a better way.

+2
source

Source: https://habr.com/ru/post/887152/


All Articles