简体   繁体   中英

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?

The local variable settingsWindow gets destructed when your function openSettingsWindow goes out of scope, you need to keep the object valid as long as you want to show your settingsWindow .

one solution would be to allocate the Window object on the heap, and use the Qt::WA_DeleteOnClose to make Qt delete the Window object for you when it is closed, here is how your openSettingsWindow would look like:

void openSettingsWindow(){
    Window* settingsWindow = new Window("Settings","icon.png");
    settingsWindow->setAttribute(Qt::WA_DeleteOnClose);
    settingsWindow->show();
}

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM