Why? A problem about Q_OBJECT and setStyleSheet().
-
A tiny code example follow:
//main.cpp #include "mainwidget.h" #include <QtWidgets/QApplication> int main(int argc, char* argv[]) { QApplication a(argc, argv); MainWidget w; w.show(); return a.exec(); }
// mainwidget.h #pragma once #include <qwidget.h> #define USE_MASK_WIDGET_BY_CLASS class MaskWidget : public QWidget { Q_OBJECT public: MaskWidget(QWidget* parent = nullptr) : QWidget(parent) { setStyleSheet("background-color:#88000000;"); if (parentWidget()) { QRect rect = parentWidget()->geometry(); rect.setX(0); rect.setY(0); setGeometry(rect); } show(); } ~MaskWidget() {} }; class MainWidget : public QWidget { Q_OBJECT public: MainWidget(QWidget* parent = nullptr); ~MainWidget(); protected slots: void onButtonClicked(); };
// mainwidget.cpp #include "mainwidget.h" #include <qpushbutton.h> static QWidget* getMaskWidget(QWidget* parent = nullptr) { auto wgt = new QWidget(parent); wgt->setStyleSheet("background-color:#88000000;"); if (wgt->parentWidget()) { QRect rect = wgt->parentWidget()->geometry(); rect.setX(0); rect.setY(0); wgt->setGeometry(rect); } return wgt; } MainWidget::MainWidget(QWidget* parent) : QWidget(parent) { setFixedSize(600, 400); auto getBtn = new QPushButton("Set mask widget", this); connect(getBtn, &QPushButton::clicked, this, &MainWidget::onButtonClicked); } MainWidget::~MainWidget() {} void MainWidget::onButtonClicked() { #ifdef USE_MASK_WIDGET_BY_CLASS auto wgt = new MaskWidget(this); #else auto wgt = getMaskWidget(this); #endif wgt->show(); }
I want to implement a simple mask widget.
You can try above code, you‘ll observe the mask not effect when define the USE_MASK_WIDGET_BY_CLASS macro. And i observe the key of this problem is the Q_OBJECT macro, while you define it at MaskWidget class , the mask will not effect, and has effect if you not define it.So, why? Will the Q_OBJECT affect the setStyleSheet() fucntion?
If you can clear my mind, thanks to much.
-
Hi and welcome to devnet,
You have to provide an implementation of paintEvent and use the Q_OBJECT macro when styling a custom widget like you do.
You have the code in the stylesheet reference under QWidget. It's juste above the list of properties part.
-
I am not sure to understand your phrase correctly.
So the rule is: if you create a QWidget subclass where you want to use style sheets, then it needs both the Q_OBJECT macro and the paintEvent reimplementation.