qtqwidget

How can I add a QWidget as a sub widget to another QWidget after init?


What I want to do is quite easy. I want to add a QLabel to a QFrame(or a QWidget) whenever I triggered some slot.

If I put the code below in MainWindow's constructor, even after ui->setupUI(this):

QLabel * pLabel = new QLabel("abc", ui->frame);

this works

However, if I move this line to a slot of MainWindow, e.g. shortcut, it won't show anything. How can I add this correct?

Note: I do not want to add it to layout. I need it overlay on others and I need to manage the exact position of it.


Solution

  • You have to call show() explicitly after creating the QLabel

    QLabel * pLabel = new QLabel("abc", ui->frame);
    pLabel->show();
    

    From the documentation:

    ...If you add a child widget to an already visible widget you must explicitly show the child to make it visible...