1
votes

I have a class MainWindow subclassing QMainWindow. As the central widget I have a QScrollArea with a QWidget inside, as a container for my own custom widgets. I set a QVBoxLayout as the layout for the QWidget container and pass this layout to the constructor of my custom class, which is supposed to dynamically create instances of my custom widget class and add them to the layout.

class MainWindow : public QMainWindow {
    Q_OBJECT
public:
    MainWindow(QWidget *parent = Q_NULLPTR);
    virtual ~MainWindow ();
private:
    QVBoxLayout mainLayout;
    QScrollArea scrollArea;
    QWidget container;
    NotificationControl control;
};

MainWindow::MainWindow (QWidget *parent) :
    QMainWindow(parent),
    container(&scrollArea),
    control(&mainLayout) {
    container.setLayout(&mainLayout);
    scrollArea.setWidget(&container);
    setCentralWidget(&scrollArea);
}

Now in my NotificationControl class I have a method addNotification:

void NotificationControl::addNotification (Notification notif) {
    qDebug() << "NotificationControl addNotification" << notif.get_app_name();
    NotificationWidget* widget = new NotificationWidget(notif);
    container->addWidget(widget);
}

When this method is called, I get the debug output, but nothing is added to the layout. But if I add this to the end of the constructor of NotificationControl...

NotificationWidget* notif = new NotificationWidget(Notification());
container->addWidget(notif);

...for some reason it works. I'm pretty sure the problem isn't the NotificationWidget class. For testing purposes I made some changes, it doesn't actually use the Notification object that is passed at all.

What could be the problem?

Edit: I just noticed that adding widgets later (not in constructor) makes the widgets added in the constructor disappear.

1

1 Answers

1
votes

Any widget added as a child widget must be explicitly shown if the parent widget is already visible. Usually, the child widgets are added before the parent widget is shown, and they then become visible themselves, too. But if you add them later, you must make them explicitly visible.