Donald Duck Donald Duck - 2 months ago 12
C++ Question

Open a new Qt window with a slot

In my Qt Program, there is a menu bar where one of the menu options is Settings. When the user click on the Settings window, it should open a Settings window. The settings window gets opened with a

openSettingsWindow()
function. This is how I made the Settings menu in the main window:

QMenu settingsMenu("&Settings");
QAction *settings = toolsMenu.addAction("&Settings");
Window::connect(settings,&QAction::triggered,&mainWindow,[&mainWindow](){
openSettingsWindow();
});
menuBar.addMenu(&toolsMenu);


mainWindow
is the main window and
Window
is the class used to create windows which inherits from
QWidget
. Its constructor takes two arguments: the title of the window and the icon of the window. This is the
openSettingsWindow()
function:

void openSettingsWindow(){
Window settingsWindow("Settings","icon.png");
settingsWindow.show();
}


The problem is that when I click ont he Settings option in the Settings menu, the Settings window opens as it should, but it closes directly after less than a second. What should I do to keep the Settings window opened?

Answer

You need to return a reference to that Window and keep it until you're no longer using it.

Window *openSettingsWindow() {
    Window *settingsWindow = new Window("Settings, "icon.png");
    settingsWindow.show();
    return settingsWindow;
}

QMenu settingsMenu("&Settings");
QAction *settings = toolsMenu.addAction("&Settings");
Window *settingsWindow = null;
Window::connect(settings,&QAction::triggered,&mainWindow,[&mainWindow, &settingsWindow](){
    settingsWindow = openSettingsWindow();
});
menuBar.addMenu(&toolsMenu);

You might want to find a better way of storing the settingsWindow pointer in the main function if you're going to have many possible open windows but this will work.

Remember to call delete() on that pointer when you're done with the settings window (likely on the window close event)