The sub-object cannot display when i add the Q_OBJECT in my code
-
I try to add a object which extend to qwidget to another widget as sub-object.but when i add the "Q_OBJECT" define in to that object,they will disappear and only show the parent qwidget.
that is my code(just for test,which show the basic formation)main.cpp :the core code
#include <QApplication> #include <QMainWindow> #include <QPushButton> #include <iostream> #include "code.h" #include "PGW.h" using namespace std; int main(int argc, char* argv[]) { QApplication a(argc, argv); code c = code(); c.show(); return a.exec(); // RenderPass(); }codecpp ,which is the parent widget
#include "code.h" #include <QPushButton> #include <iostream> #include <QDebug> #include <QVulkanWindow> #include <QVulkanInstance> #include "PGW.h" //#include "render.h" using namespace std; code::code() { this->setGeometry(0,0,1000,1000); m* w = new m(this); w->setGeometry(0, 0, 100, 100); w->setStyleSheet("background-color: red;"); w->show(); } code::~code() { }PGW.cpp,which is the sub-object
#include "PGW.h" m::m(QWidget* p) : QWidget(p) { } m::~m() {}and this is the header files:
code.h:#include "code.h" #include <QPushButton> #include <iostream> #include <QDebug> #include <QVulkanWindow> #include <QVulkanInstance> #include "PGW.h" //#include "render.h" using namespace std; code::code() { this->setGeometry(0,0,1000,1000); m* w = new m(this); w->setGeometry(0, 0, 100, 100); w->setStyleSheet("background-color: red;"); w->show(); } code::~code() { }PGW.h:
#include <QWidget> class m : public QWidget { Q_OBJECT //remove this can make this widget show public: m(QWidget* p= nullptr); ~m(); }; `` -
code::code() { this->setGeometry(0,0,1000,1000); m* w = new m(this); w->setGeometry(0, 0, 100, 100); w->setStyleSheet("background-color: red;"); w->show(); }Is
wsupposed to be shown on top of thecodewidget, laid out inside thecodewidget, or completely independent of thecodewidget? -
it not independent,and today i discover that if the m extend to qpushbutton or qlable,all is current(althougt i add the define of "Q_OBJECT“).but if i change it to qwidget,is cannot finded in parent widget
@ctrkalk Then I know the reason, it is not that it doesn't show, but the stylesheet doesn't work, so the widget is totally transparent.
There're already quite a lot posts in the forum asking about subclassed QWidget's stylesheet not working.
It is also documented:If you subclass from QWidget, you need to provide a paintEvent for your custom QWidget as below:
...But this is the first time I know that a subclassed QWidget without Q_OBJECT would have stylesheet working :)
BTW, the simplest solution for this kind of problem (if you don't want to reimplement paintEvent) is to subclass QFrame instead of QWidget, or using palette instead of stylesheet.
-
C ctrkalk has marked this topic as solved on