Label doesn't show up



  • Hi.

    I have this simple piece of code:

    @#include <QApplication>
    #include <QLabel>

    int main (int argc, char *argv[]) {
    QApplication app(argc, argv);
    QWidget w;
    w.setGeometry (0, 0, 800, 450);
    QLabel a("AAA", &w);
    a.setGeometry (10, 10, 200, 100);
    w.showNormal ();
    QLabel b("BBB", &w);
    b.setGeometry (10, 410, 200, 100);
    w.update ();
    return app.exec ();
    }@

    When I run it, I see "AAA" but not "BBB". Why is that? It must be possible to add a child widget to 'w' after it's been shown!

    I'm using Qt 5.4.0 on Ubuntu 14.10.


  • Moderators

    One problem is that you placed the B label below the bottom border of the widget. A rectangle of height 100 placed at y 410 will try to render text somewhere around y 460, which is lower than the bottom border (450).

    The other problem is described in the docs of "QWidget":http://doc.qt.io/qt-5/qwidget.html#QWidget

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

    So all you need to do is this:
    @
    QLabel b("BBB", &w);
    b.setGeometry (10, 410, 200, 100);
    b.show();
    @
    You don't need the call to w.update().



  • Comments were removed even though I still believe that code which rely on the object order destruction in the same scope is evil.


  • Moderators

    @alex_malyu This code is fine (for a code snippet). Order of destruction of scope variables is guaranteed by the standard and is the reverse order they were declared in. So
    @
    //this is perfectly fine:
    QWidget parent1;
    QWidget child1(&parent1); //will destruct first and detach from parent

    //this is an error:
    QWidget child2;
    QWidget parent2;
    child2->setParent(&parent2); //a double delete will occur on scope exit
    @

    The setGeometry call is setting the position in parent coordinates, so yes, they are related. The widget is just not shown initially if the parent is already visible. This is done to allow creating hidden widgets without a flicker. If they were shown initially you would have to call hide() right away but they might still be shown for a moment causing a distraction. They are shown automatically for not yet shown parents because there's no such problem there.

    Layouts should be used most of the time, but some simple non-resizable widgets can do without them fine (less typing).



  • Ok, Thanx a lot for your help!!


  • Moderators

    [quote author="alex_malyu" date="1423617598"]Comments were removed even though I still believe that code which rely on the object order destruction in the same scope is evil.[/quote]
    Agreed. But for small examples or snippets to illustrate an issue it's ok.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.