问题描述
如果我单击“确定”按钮,则想从一个消息框中关闭主窗口。
class usb_boot : public Gtk::Window{
public:
usb_boot();
并从消息框中
我尝试过
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;
}
如何关闭主窗口?
解决方法
您应尽可能避免使用原始的new
/ delete
(例如,在这里)。对于消息对话框,可以使用简单的作用域:
#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);
}
此外,在您的代码中,您调用usb_boot().close()
,但请注意usb_boot
之后的多余括号。这将构造一个新的usb_boot
对象(因为您调用了构造函数)并立即将其关闭。在上面的示例中,我叫w.close()
,而不是MainWindow().close()
。