0
votes

I try to create a custom widget like this:

device.h

class Device : public QWidget
{
    Q_OBJECT
public:
    explicit Device(QWidget *parent = 0);
};

device.cpp

Device::Device(QWidget *parent) :
    QWidget(parent)
{
    setGeometry(QRect(0, 0, 100, 100));
    setStyleSheet(QString::fromUtf8("background: black;"));
    raise();

    setVisible(true);

    qDebug() << "is visible: " << isVisible();
}

The constructor tries to create the square widget with black background. But I see nothing on my MainWindow and have output like:

is visible:  false 

It seems I create the device object correctly (ui->centralWidget is parent):

// MainWindow constructor
// device and button pointers defined in mainwindow.h

device = new Device(ui->centralWidget);
button = new QPushButton("Push me!", ui->centralWidget);

I think I could see black square with button or only black square overlaped the button. But I see only the button without any square.

It is not clear for me even because I call setVisible(true) and get isVisible() as false in the next line. But the button (the same child of QWidget) is visible. Where is difference?

1
Is the parent visible at that time? Perhaps you want isVisibleTo()?Toby Speight
@TobySpeight, yes, it is visible. I see the push button (that is the sibling)Bogdan
If you turn your code fragments into a minimal reproducible example, we might be able to work out where you're going wrong.Toby Speight
You say But the button (the same child of QWidget) is visible, why do you say that the button is visible?, please provide a minimal reproducible exampleeyllanesc
@Bogdan you could provide a minimal reproducible example, why do you say that the device object is not visible, ignoring what is printed in the console?eyllanesc

1 Answers

0
votes

The parent widget is likely invisible. Order of events matter, if the parent becomes visible after the constructor of Device, then the isVisible will work as intended when called from a different function after it is displayed. Otherwise, if the parent widget is hidden, all of it's children widgets are also hidden (even if you explicitly state otherwise for the children widgets). When do you call show() on the parent widget? Without a Minimal, Complete, and Verifiable Example we can only speculate.