zoukankan      html  css  js  c++  java
  • 关闭主窗口时触发关闭所有打开的其他非模式窗口

    QT 关闭主窗口时触发关闭所有打开的其他窗口

    1.用的信号/槽实现

    在main函数中将QApplication::lastWindowClosed()信号和QApplication::quit()槽函数相关联

    a.connect( &a, SIGNAL( lastWindowClosed() ), &a, SLOT( quit() ) );
    void QApplication::lastWindowClosed () //[signal] 后面有QT助手的解释,明显没有我的方法简单方便
    

    2.设置窗口参数 Qt::WA_QuitOnClose attribute,为true 的所有窗口关闭后程序退出.

    主窗口设置属性Qt::WA_QuitOnClose

    w.setAttribute(Qt::WA_QuitOnClose,true);
    

    其他窗口

    XX.setAttribute(Qt::WA_QuitOnClose,false);
    

    这样关闭主窗口的时候,主程序就会退出,其他窗口也会关闭。

    3.这两步就完成了任务.不过为了方便,我们可以把其他窗口类的构造函数中加一句

    setAttribute(Qt::WA_QuitOnClose,false);
    

    就不用为每个生成的窗体添加属性了.

    4.再进一步,我们分析一下QT源码

    void QApplication::setQuitOnLastWindowClosed(bool quit)
    {
        QApplicationPrivate::quitOnLastWindowClosed = quit;
    }
    

    setQuitOnLastWindowClosed(bool quit)函数也就是设置了一下QApplicationPrivate::quitOnLastWindowClosed这个值.
    然后

    void QApplicationPrivate::emitLastWindowClosed()
    {
        if (qApp && qApp->d_func()->in_exec) {
            if (QApplicationPrivate::quitOnLastWindowClosed) {
                // get ready to quit, this event might be removed if the
                // event loop is re-entered, however
                QApplication::postEvent(qApp, new QEvent(QEvent::Quit));
            }
            emit qApp->lastWindowClosed();
        }
    }
    

    也发射了信号

    emit qApp->lastWindowClosed();
    所以两种方法其实是一样滴.

    下面是别人的总结

    QT 关闭主窗口,触发关闭所有打开的窗口
    主窗口设置属性Qt::WA_QuitOnClose

    w.setAttribute(Qt::WA_QuitOnClose,true);

    Qt::WA_QuitOnClose属性是使窗口如果是最后一个关闭的时候触发事件lastWindowClosed();

    然后主程序收到事件退出
    a.connect( &a, SIGNAL( lastWindowClosed() ), &a, SLOT( quit() ) );

    现在问题是自己定义的子窗口打开的时候,它们默认Qt::WA_QuitOnClose也是true,所以如果主窗口关闭的时候有别的窗口开着,(除了一些暂时性的窗口——如启动界面、工具窗口、弹出菜单)程序还是不会退出,而是等到最后一个窗口关闭之后才退出。

    所以现在要把别的窗口的Qt::WA_QuitOnClose设为false。

    XX.setAttribute(Qt::WA_QuitOnClose,false);

    这样关闭主窗口的时候,主程序就会退出,其他窗口也会关闭。

    qt助手中的解释:

    void QApplication::lastWindowClosed () [signal]

    This signal is emitted from QApplication::exec() when the last visible primary window (i.e. window with no parent) with the Qt::WA_QuitOnClose attribute set is closed.

    By default,

    this attribute is set for all widgets except transient windows such as splash screens, tool windows, and popup menus

    QApplication implicitly quits when this signal is emitted.

    This feature can be turned off by setting quitOnLastWindowClosed to false.

    附:
    Qt销毁非模态对话框

  • 相关阅读:
    [转][LeetCode]Longest Common Prefix ——求字符串的最长公共前缀
    [转]最长回文子串——4种解法
    [转]通过金矿模型介绍动态规划
    一句话说清楚什么是闭包函数
    [转]as3事件流机制彻底理解
    Eclipse 快捷键
    文件打包与解压缩
    第5节 环境变量与文件查找
    vim的多标签
    java思维导图
  • 原文地址:https://www.cnblogs.com/kuikuitage/p/12811780.html
Copyright © 2011-2022 走看看