Question

I have a simple program and I cannot remember how to use multiple Ui form classes in the same program. I have the MainWindow class, which has a button, which opens the Browser class. The classes are pretty much their defaults, and this is what I use to open the Browser class ui:

void MainWindow::on_pushButton_2_clicked()
{
    this->hide();
    Browser browser;
    browser.show();
}

The constructor in Browser is simple ui->setupUi(this).

What happens is the Browser window opens and then closes immediately.

Was it helpful?

Solution

You may create the Browser on the heap, i.e.:

Browser* browser=new Browser(this);
browser->show();

because I assume it is not modal.

OTHER TIPS

That is because you are allocating the browser object on the stack, and then it immediately gets destroyed at the end of the function.

void MainWindow::on_pushButton_2_clicked()
{
    hide();
    Browser browser; // <--- constructed
    browser.show();
}                    // <--- destructed

You have two options to fix it:

  • Make it a heap object with "this" as the parent. This will make sure that the object is not destroyed at the end of your function, but will not leak either because when the parent gets destroyed, the children get automatically destroyed, too, with the Qt parent/child hierarchy.

    void MainWindow::on_pushButton_2_clicked()
    {
        hide();
        Browser *browser = new Browser(this);
        browser->show();
    }           
    
  • Make it as a class member. This will outlive the scope of the function, so it will be fine.

    void MainWindow::on_pushButton_2_clicked()
    {
        hide();
        m_browser.show();
    }
    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top