0
votes

I'm trying to add an objects (that inherits from QWidget) as a child to another QWidget as shown below, it works perfectly with another normal QWidget instance but not with my custom class, any idea why ?

fenetre.h

#ifndef FENETRE_H
#define FENETRE_H

#include <QWidget>
#include <QMouseEvent>

class Fenetre : public QWidget
{
   Q_OBJECT
public:
   Fenetre();
};

#endif // FENETRE_H

fenetre.cpp

#include "fenetre.h"

Fenetre::Fenetre() : QWidget()
{

}

main.cpp

#include <iostream>
#include <QApplication>
#include <QWidget>
#include "fenetre.h"

int main(int argc, char *argv[])
{
    QApplication app(argc,argv);

    QWidget window;
    window.setFixedSize(800,600);

    //This appears
    QWidget rec1;
    rec1.setParent(&window);
    rec1.setFixedSize(100,100);
    rec1.move(400,200);
    rec1.setStyleSheet("background-color: red");

    //This one not
    Fenetre rec2;
    rec2.setParent(&window);
    rec2.setFixedSize(100,100);
    rec2.move(200,200);
    rec2.setStyleSheet("background-color: green");

    window.show();

    return app.exec();
}

PS: I did research on the platform, but the majority of the answers speak of the use of a layout. Thank you !

1
I tried to reproduce your MCVE with Windows10/VS2017/Qt5.13 as well as with cygwin/g++/Qt5.9. In both cases, I got red and green box. The only change I did: exclude Q_OBJECT from class fenetre (as I wasn't able to involve moc properly and haven't any experience with it). In this MCVE, Q_OBJECT is probably rather useless - not sure if it plays a role for your issue... - Scheff's Cat
@Scheff thank you, the problem was the setStyleSheet() function, I had to implement the paintEvent function in my custom class to make it work. - ganzo db
What do you do in fenetre::paintEvent()? It should be inherited from QWidget(), shouldn't it? In my case, it worked without paintEvent(). I just copy/pasted your code and the only thing I did was to change Q_OBJECT into //Q_OBJECT. Could it be that introducing a new meta-type for class fenetre has such consequences? - Scheff's Cat
According to this wiki, we need to provide a paintEvent to the custom widget - ganzo db
This wiki mentioned Symbian OS. I didn't need a paintEvent(). (I swear.) ;-) On what OS, you did run your test? - Scheff's Cat

1 Answers

0
votes

you miss the parent:

//header .h
class Fenetre : public QWidget
{
   Q_OBJECT
public:
   Fenetre(QWidget *parent = 0);
};

//source .cpp
Fenetre::Fenetre(QWidget *parent) : QWidget(parent)
{

}