Donald Duck Donald Duck - 1 month ago 7x
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

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

QMenu settingsMenu("&Settings");
QAction *settings = toolsMenu.addAction("&Settings");

is the main window and
is the class used to create windows which inherits from
. Its constructor takes two arguments: the title of the window and the icon of the window. This is the

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

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?


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");;
    return settingsWindow;

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

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)