[Solved] Open new UI -> Closes immediately



  • Hello, I've got a more or less simple question. I'm trying to open a second UI (settings.ui) when a user presses a specific button. It works, but the UI closes again immadiately. Here's the code:

    @settings settingsUi;
    settingsUi.setAttribute(Qt::WA_DeleteOnClose);
    settingsUi.show();@

    Can anyone help me with this?


  • Lifetime Qt Champion

    Hi,

    I suppose you have something like:
    @
    void MyWidget::myFunction(){
    settings settingsUi;
    settingsUi.setAttribute(Qt::WA_DeleteOnClose);
    settingsUi.show();
    }
    @

    After calling show(), your settings variable goes out of scope so it's destroyed.

    You need to either exec() rather than show() it or allocate in on the heap



  • Thank you, I already managed it myself. Here's what I did:

    mainwindow.h
    @#include <newdialog.h>
    ...
    public slots:
    void openSettings();
    ...
    private:
    Ui::MainWindow *ui;
    NewDialog *m_dialogSettings;
    };@

    mainwindow.cpp:
    @void MainWindow::openSettings()
    {
    m_dialogSettings = new NewDialog();
    m_dialogSettings->show();
    m_dialogSettings->raise();
    m_dialogSettings->activateWindow();
    }@
    Then I called it with openSettings(). Simple. Thanks for your help though!


  • Lifetime Qt Champion

    But now you have a memory leak. Each time you call openSettings you create a new "NewDialog" and replace the old one without deleting it.



  • True, checked it with the TaskManager. The dialog stays in the memory. Couldn't I do something like this?

    @void MainWindow::openSettings()
    {
    m_dialogSettings = new Dialog();
    if(m_dialogSettings){
    m_dialogSettings->close();}
    m_dialogSettings->show();
    m_dialogSettings->raise();
    m_dialogSettings->activateWindow();
    }@

    /edit: Wrong solution. This works:
    @Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
    {
    Dialog::setAttribute(Qt::WA_DeleteOnClose);
    ui->setupUi(this);
    }@
    It's my new constructor for the Dialog.


  • Lifetime Qt Champion

    @Dialog::setAttribute(Qt::WA_DeleteOnClose);@

    Should throw an error since you are trying to call a non static function without any object.

    @
    m_dialogSettings = new Dialog();
    if(m_dialogSettings){
    m_dialogSettings->close();}
    @

    Doesn't really make sense, you close the dialog each time you call this function then show it again, and you still have the memory leak.


Log in to reply
 

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