Why doesn't Qt use this style selector type?

I have this small test script that should display two widgets, with one completely overlapping the other. One of them is translucent, so the other widget should shine through it.

To this end, I set the stylesheet in one widget using a selector of type Menu (which is its class name). But instead of making the widget opaque with a factor of 200/255 , it makes it completely translucent, as if the type selector is not applicable to the menu object at all, so that I no longer see the blue glow.

If I use the selector * instead, it works as expected. I checked the value of metaObject()->className() , which correctly tells Menu . Can someone hint me at the mistake I made, please? This is a smaller test file of a real program that shows much weirder behavior, and I want this reduced test file to work first.

 #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(); } 
+4
source share
1 answer

When using style sheets with subclasses of QWidget you must override paintEvent as follows:

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

See the stylesheet link from the Qt documentation .

+9
source

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


All Articles