qt 关闭一个页面,结束应用程序运行,关闭其他窗口


在一个PC端的应用中,经常会出现关闭主窗体,进而需要把所有打开的窗体都随着关闭,结束程序的情况,那么具体怎么实现呢?

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

      a.connect(&a,SIGNAL(lastWindowClosed()),&a,SLOT(quit()));

2、将主窗口的属性设置为QWidget::setAttribute(WA_QuitOnClose,true);其他窗口该属性设置为false:

      注意:在初始化窗口时就要设置,不是在窗口的构造函数里设置

    Princekin w;
    w.setWindowFlags(Qt::WindowCloseButtonHint|Qt::WindowMinimizeButtonHint|Qt::FramelessWindowHint);
    w.setAttribute(Qt::WA_QuitOnClose,true);
    w.show();

具体可参考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.


  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Qt中,关闭窗口结束程序可以通过以下几种方式实现: 1. 使用close()函数:在Qt中,每个窗口都有一个close()函数,调用该函数可以关闭当前窗口。如果该窗口应用程序的主窗口,则关闭窗口会导致整个应用程序退出。 示例代码: ```cpp #include <QApplication> #include <QMainWindow> int main(int argc, char *argv[]) { QApplication app(argc, argv); QMainWindow mainWindow; mainWindow.show(); return app.exec(); } ``` 在上述示例代码中,当用户关闭窗口时,应用程序会自动退出。 2. 使用QCoreApplication的quit()函数:QCoreApplication是Qt中的核心应用程序类,它提供了一些与应用程序控制相关的函数。其中,quit()函数可以用于退出应用程序。 示例代码: ```cpp #include <QApplication> #include <QMainWindow> #include <QAction> int main(int argc, char *argv[]) { QApplication app(argc, argv); QMainWindow mainWindow; QAction *exitAction = new QAction("Exit", &mainWindow); QObject::connect(exitAction, &QAction::triggered, &app, &QCoreApplication::quit); mainWindow.menuBar()->addAction(exitAction); mainWindow.show(); return app.exec(); } ``` 在上述示例代码中,创建了一个菜单栏,并添加了一个"Exit"菜单项。当用户点击"Exit"菜单项时,会触发exitAction的triggered信号,从而调用QCoreApplication的quit()函数退出应用程序。 3. 使用QApplication的quit()函数:QApplication类继承自QCoreApplication,它提供了一些与GUI相关的函数。其中,quit()函数可以用于退出应用程序。 示例代码: ```cpp #include <QApplication> #include <QMainWindow> #include <QPushButton> int main(int argc, char *argv[]) { QApplication app(argc, argv); QMainWindow mainWindow; QPushButton *exitButton = new QPushButton("Exit", &mainWindow); QObject::connect(exitButton, &QPushButton::clicked, &app, &QApplication::quit); mainWindow.setCentralWidget(exitButton); mainWindow.show(); return app.exec(); } ``` 在上述示例代码中,创建了一个窗口,并添加了一个"Exit"按钮。当用户点击"Exit"按钮时,会触发exitButton的clicked信号,从而调用QApplication的quit()函数退出应用程序

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值