Qt 优雅的结束程序

说明:项目要求设计系统退出按键,参照的各大APP都有安全结束程序功能。

1、了解Qt内存管理中的堆分配机制

  继承与C++的new、delete与Qt自身的deleteLater()。new与delete应一对一出现,deleteLater()可以代替delete。

deleteLater()的原理是:QObject::deleteLater()并没有将对象立即销毁,而是向主消息循环发送了一个event,下一次

主消息循环收到这个event之后才会销毁对象。 这样做的好处是可以在这些延迟删除的时间内完成一些操作,坏处就

是内存释放会不及时。

2、了解Qt对象析构机制

  Qt使用家族树的形式管理对象。当指定了“父窗口”之后,该窗口的析构就由父窗口来接管,Qt会保证在合适的时

候析构该窗口,并且只析构一次。

3、匹配析构

  1、在没有指定父对象的前提下,需要手动析构,或者setAttribute(Qt::WA_DeleteOnClose,true);(如果此

属性为true,则当最后一个可见的主窗口(即没有父窗口的窗口)关闭时,应用程序将退出。)

  2、在指定了父对象之后,除非你想提前关闭,不然不需要任何操作,子窗口会跟随父窗口销毁。

注意:两种方法都需要写好析构函数,析构那些没有关系树的new对象。

4、举例

例子1:

//构造函数
Mainwindow::Mainwindow(QWidget *parent):
    QWidget(parent),
    pbridge(new CBridge)
{
    ui_voyage       = new Voyage();
    ui_navigator    = new Navigator();
    ui_setup        = new SetUp();
    ui_group        = new Group();
    ui_playback     = new PlayBack();
    ui_keyboard     = new KeyBoard();
    mainwindowtips  = new MessageTips();
    calib20mintimer = new QTimer(this);
#if DEBUG_FLAGE
    ui_debug     = new Debug();
#endif
}
//析构函数
Mainwindow::~Mainwindow()
{
    if( pbridge != NULL ){pbridge->deleteLater();}
    if( ui_navigator != NULL ){ui_navigator->close();}
    if( ui_group != NULL ){ui_group->close();}
    if( ui_playback != NULL ){ui_playback->close();}
    if( ui_keyboard != NULL ){ui_keyboard->close();}
    if( ui_setup != NULL ){ui_setup->close();}
#if DEBUG_FLAGE
    if( ui_debug != NULL ){delete ui_debug;ui_debug = NULL;}
#endif
    if( mainwindowtips != NULL ){mainwindowtips->close();}
}

说明:其中calib20mintimer为QTimer类,父对象为MainWindow,故不需要手动析构

例子2:

//构造函数
CBridge::CBridge(QObject *parent) :
    QObject(parent)
{
    keyBusiness         = new Business_Key();
    logBusiness         = new Business_Log(this);
    
    waterdepthBusiness  = new Business_WaterDepth(this);
    underwaterBusiness  = new Business_UnderWater(this);
    insBusiness         = new Business_Ins(this);
    batteryBusiness     = new Business_Battery(this);
    dataStorage         = new DataStorage(this);

    waterdepthSerial    = new Serial_WaterDepth(this);
    underwaterSerial    = new Serial_UnderWater(this);
    insSerial           = new Serial_Ins(this);
}
//析构函数
CBridge::~CBridge()
{
    if( keyBusiness!=NULL ){ keyBusiness->deleteLater(); }
}
原文地址:https://www.cnblogs.com/shuoguoleilei/p/13724036.html