Important: Please read the Qt Code of Conduct -

Closing main window and open another one.

  • Hi,

    I'm trying to create a menu window with several QPushButtons so that, depending on which QPushButton the user clicks, the menu window closes and another one opens.

    class Window_A : public QObject
    		QMainWindow MyWindow;
    		QWidget MyWidget;
    		// Some other stuff, including a QPushButton to call the public slot "showWindow_B"
    	public slots:
    		void show(void);
    		void showWindow_B(void);

    And then the functions are defined as follows:

    Window_A::Window_A(void) : QObject()
    	MyWindow.setFixedSize(300, 200);
    void Window_A::show(void)
    void Window_A::showWindow_B(void)
    	std::shared_ptr<Window_B> foo = std::make_shared<Window_B>();

    (Same code for the class Window_B)

    int main(int argc, char *argv[])
    	QApplication app(argc, argv);
    	Window_A foo;;
    	return app.exec();

    However, when I run it and click the appropriate QPushButton so that Window_A::showWindow_B is called, the first window (Window_A) disappears (good) but the new window (Window_B) does not appear (not good). Could anyone point out to me what exactly I'm doing wrong?

    Thanks in advance :)

  • Lifetime Qt Champion


    foo is destroyed at the end of showWindow_B so your Window_B gets destroyed at the same time thus you don't see it.

    Hope it helps

  • @SGaist

    Thanks for your reply. I'm not sure I understand though, how could foo be destroyed, it's a shared_ptr ?

  • Lifetime Qt Champion

    Even if it's a shared_ptr, it's a class that obeys the same rules as any other. You create your shared pointer locally in your function. It will get destroyed at the end of the function. And since it's the only shared_ptr containing your widget, the widget will get destroyed alongside the shared_ptr object.

    More information here

  • @SGaist Thanks a bunch!

Log in to reply