Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't Qt apply this style sheet type-selector?

I have this little test-case which is supposed to show two widgets, with one overlapping the other completely. The one is translucent so the other widget should shine through it.

For that purpose, I set a style sheet on the one widget using a type-selector Menu (which is its class name). But instead of making the widget opaque by a factor of 200/255, it makes it completely translucent as if the type-selector doesn't apply at all to the menu object, so that I see no shine of blue anymore.

If I instead use the * selector, it works as expected. I tested the value of metaObject()->className(), which correctly reports Menu. Can anyone hint me to the error I have made please? This is a reduced testcase of a real program which shows a much more weird behavior, and I first want to make this reduced testcase work.

#include <QtGui/QApplication>
#include <QtGui/QWidget>
#include <QtGui/QLayout>
#include <QtGui/QVBoxLayout>
#include <QtGui/QLabel>
#include <QtGui/QResizeEvent>

class Menu: public QWidget {
   Q_OBJECT

public:
   Menu(bool translucent, QWidget *p):QWidget(p) {
      if(translucent) {
         setStyleSheet("Menu { background-color: rgba(0, 0, 150, 200) }");
      }

      QLabel *label = new QLabel(
         translucent ? "\n\nHello I'm translucent" : "I'm not translucent");
      label->setStyleSheet("color: white; font-size: 20pt");

      QLayout *mylayout = new QVBoxLayout;
      setLayout(mylayout);
      mylayout->addWidget(label);
   }
};

class MyWindow : public QWidget {
public:
    MyWindow() {
      Menu *m1 = new Menu(false, this);
      Menu *m2 = new Menu(true, this);

      m1->lower();
      m2->raise();
    }

protected:
    void resizeEvent(QResizeEvent *event) {
       foreach(QWidget *w, findChildren<QWidget*>()) {
         w->setGeometry(0, 0, width(), height());
       }
    }
};

int main(int argc, char **argv) {
   QApplication app(argc, argv);
   MyWindow w;
   w.show();
   app.exec();
}
like image 671
Johannes Schaub - litb Avatar asked Dec 27 '22 04:12

Johannes Schaub - litb


1 Answers

When using stylesheets with QWidget subclasses, you are supposed to override paintEvent this way:

void Menu::paintEvent(QPaintEvent *)
{
    QStyleOption opt;
    opt.init(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}

See the stylesheet reference from Qt documentation.

like image 200
Chris Browet Avatar answered Jan 08 '23 06:01

Chris Browet