Important: Please read the Qt Code of Conduct -

Window not showing up using show()

  • I have some code for opening a window from the main one, but it doesn't work. "Window open." gets printed, then nothing else happens, it's just as if show() didn't do anything. This is invoked from a menu using a connector and an action.

    The relevant code:

    void test1::openNewWindow()
    qWarning( "Window open." );
    QWidget w(this);
    Ui::dialog ventanados;

  • Hi! The problem is that you create the window on the stack inside openNewWindow(), so it gets destroyed immediately when the function returns.

    void test1::openNewWindow()
    qWarning( "Window open." );
    QWidget w(this); // <-- w is local to this scope
    Ui::dialog ventanados;
    } // <-- scope ends, w gets destroyed

  • @Wieland thank you. I have tried it and it is an excellent answer, but I don't still get the clue. I have added a 1sec delay to the function after calling show() to see if the windows appears, no luck. I have made the changes you have proposed, and I now have the following code:


    #ifndef test1_H
    #define test1_H
    #include <QMainWindow>
    #include <QWidget>
    #include "ui_test1.h"
    class test1 : public QMainWindow
    public slots:
       void openNewWindow();
        QWidget *w;
        Ui::dialog ventanados;
    #endif // test1_H


    #include "test1.h"
    #include <QLabel>
    #include <QMenu>
    #include <QMenuBar>
    #include <QAction>
    #include <QDialog>
    #include <QtTest/QTest>
        w = new QWidget(this);
        QLabel* label = new QLabel( this );
        label->setText( "Hello World!" );
        setCentralWidget( label );
        QAction* action = new QAction(this);
        action->setText( "Open new window" );
        connect(action, SIGNAL(triggered()), SLOT(openNewWindow()) );
        menuBar()->addMenu( "File" )->addAction( action );
    void test1::openNewWindow()

  • The following creates a widget that is a child of your MainWindow:

    w = new QWidget(this);

    If you want w to be a window on its own, then call the constructor without a parent:
    w = new QWidget();

  • OMG, thanks!!!

  • Moderators

    Parents are important for stacking order and focus management. What's more is in your code you're not deleting it explicitly, so if you don't give it a parent it will leak.
    Better than not giving it a parent would be to either use QDialog instead or make it a window via a flag, i.e.:

    w = new QWidget(this, Qt::Window);

  • It also works! Thank you.

Log in to reply