Qt::WA_QuitOnClose

当Qt应用程序中的最后一个具有特定属性的窗口关闭时,系统默认会退出应用。可以通过设置QApplication::quitOnLastWindowClosed属性来改变这一行为。若希望在主窗口关闭时同时关闭所有子窗口,需为子窗口设置setAttribute(Qt::WA_QuitOnClose, false),以确保在主窗口关闭时触发全部窗口的关闭。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

帮助文档中的解释:
Makes Qt quit the application when the last widget with the attribute set has accepted closeEvent(). This behavior can be modified with the QApplication::quitOnLastWindowClosed property. By default this attribute is set for all widgets of type Qt::Window.

当最后一个具有属性集的窗口小部件接受closeEvent()时,使Qt退出应用程序。
QT中窗口默认Qt::WA_QuitOnClose为true,如果主窗口关闭时还有自定义窗口打开,则该自定义的程序还是不会退出,而是等到最后一个窗口关闭之后才退出。
所以要设setAttribute(Qt::WA_QuitOnClose,false)才能QT 关闭主窗口,触发关闭所有打开的窗口。

简单的说就是如果想要主窗口关闭时,同是关闭子窗口,那么子窗口要设置:
this->setAttribute(Qt::WA_QuitOnClose,false);

qt程序如下: mainwindow.cpp 的内容: #include "mainwindow.h" #include <QSqlDatabase> #include <QDebug> #include <QSqlQuery> #include <QMessageBox> #include <libpq-fe.h> #include <stdio.h> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { qDebug() << "available drivers:"; QStringList drivers = QSqlDatabase::drivers(); foreach (QString driver, drivers) qDebug() << driver; QSqlDatabase db = QSqlDatabase::addDatabase("QPSQL"); db.setHostName("127.0.0.1"); // 需要改成自己的对应的端口号 db.setDatabaseName("highgo"); // 数据库名称,需要改成自己的 db.setPort(5866); // 端口号,需要改成自己的 db.setUserName("sysdba"); // 用户名,需要改成自己的 db.setPassword("Hello@1234567"); // 用户密码,需要改成自己的 if (db.open()) { QMessageBox::information(this, "Info", "Database connection successful"); // 执行查询语句 QSqlQuery query; if (query.exec("SELECT version();")) { if (query.next()) { // 获取查询结果 QString version = query.value(0).toString(); QMessageBox::information(this, "Database Version", version, QMessageBox::Yes | QMessageBox::No ); } else { QMessageBox::warning(this, "Query Error", "No data returned from query"); } puts("44444"); } else { QMessageBox::warning(this, "Query Error", "Failed to execute query"); } puts("55555"); } else { QMessageBox::critical(this, "Error", "Failed to open database"); } db.close(); puts("33333"); //setAttribute(Qt::WA_DeleteOnClose); } MainWindow::~MainWindow() { puts("77777"); } main.cpp 的内容: #include "mainwindow.h" #include <QApplication> #include <stdio.h> int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); w.close(); printf("22222"); return a.exec(); } mainwindow.h 的内容: #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = NULL); ~MainWindow(); private: Ui::MainWindow *ui; }; #endif // MAINWINDOW_H 程序执行后 ,数据库能登录上,也有查询结果,但程序卡住没有关闭,终端输出 44444 55555 33333
最新发布
03-26
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值