Search code examples
c++gtkmm3

Close main window ffrom messagebox using gtkmm / c++


From a message box i'd like to close the main window if i click on Ok button.

class usb_boot : public Gtk::Window{

public:
    usb_boot();

and from message box

i tried this

void usb_boot::creation(){
//Gtk::MessageDialog dialog(*this, dropdownList.get_active_text());
std::string message("Format : " + type);
Gtk::MessageDialog *dialog = new Gtk::MessageDialog("Resume", true, Gtk::MESSAGE_QUESTION, Gtk::BUTTONS_YES_NO);
dialog->set_title("Resume");
dialog->set_message(dropdownList.get_active_text());
dialog->set_secondary_text(message);
dialog->set_default_response(Gtk::RESPONSE_YES);
int result = dialog->run();

switch(result){

    case(Gtk::RESPONSE_YES):{

        std::cout << "next program" << std::endl;
        delete dialog;// ok work
        usb_boot().close();//compile but doesn't close main window
        break;
    }

How to close the main window ?


Solution

  • You should avoid using raw new/delete whenever you can (like here, for instance). For message dialogs, you can use simple scopes:

    #include <iostream>
    #include <gtkmm.h>
    
    class MainWindow : public Gtk::ApplicationWindow
    {
    
    public:
        MainWindow() = default;
    
    };
    
    int main(int argc, char **argv)
    {
        auto app = Gtk::Application::create(argc, argv, "so.question.q63872817");
        
        MainWindow w;
        w.show_all();
        
        int result;
        // Here we put the dialog inside a scope so that it is destroyed
        // automatically when the user makes a choice (you could do it
        // inside a function instead of a free scope):
        {
            Gtk::MessageDialog dialog(w, "Message dialog", true, Gtk::MESSAGE_QUESTION, Gtk::BUTTONS_YES_NO);
            dialog.set_title("Title");
            dialog.set_message("Primary message");
            dialog.set_secondary_text("Secondary message");
            dialog.set_default_response(Gtk::RESPONSE_YES);
            
            result = dialog.run();
            
        } // Here the dialog is destroyed and closed.
        
        if(result == Gtk::RESPONSE_YES)
        {
            std::cout << "Closing main window..." << std::endl;
            //MainWindow().close(); // Will not work!
            w.close();
        }
    
        return app->run(w);
    }
    

    Also, in your code, you call usb_boot().close(), but notice the extra parenthesis after usb_boot. This constructs a new usb_boot object (since you call the constructor) and immediately closes it. In the example above, I called w.close(), instead of MainWindow().close().