【问题标题】:Why doesn't Qt apply this style sheet type-selector?为什么 Qt 不应用这个样式表类型选择器?
【发布时间】:2012-03-23 03:31:44
【问题描述】:

我有这个小测试用例,它应该显示两个小部件,一个完全重叠另一个。一个是半透明的,所以另一个小部件应该通过它发光。

为此,我使用类型选择器Menu(这是它的类名)在一个小部件上设置了样式表。但是,它并没有使小部件不透明200/255,而是使它完全透明,好像类型选择器根本不适用于菜单对象,所以我再也看不到蓝色的光芒了。

如果我改用 * 选择器,它会按预期工作。我测试了metaObject()->className() 的值,它正确地报告了Menu。任何人都可以提示我我犯的错误吗?这是一个真实程序的简化测试用例,它表现出更奇怪的行为,我首先想让这个简化的测试用例工作。

#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();
}

【问题讨论】:

    标签: c++ qt qt4 qtstylesheets


    【解决方案1】:

    当使用带有QWidget 子类的样式表时,您应该以这种方式覆盖paintEvent

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

    请参阅stylesheet reference from Qt documentation

    【讨论】:

    • 哇,我完全不知道。谢谢。
    猜你喜欢
    • 2019-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-02
    • 2011-11-21
    • 2011-01-18
    • 2013-07-31
    • 1970-01-01
    相关资源
    最近更新 更多