您可以使用QMessageBox来实现在点击关闭按钮时弹出提示窗口,并在点击OK按钮时退出应用程序的功能。以下是一个示例代码:

#include <QApplication>
#include <QMainWindow>
#include <QMessageBox>

class MainWindow : public QMainWindow
{
public:
    MainWindow(QWidget *parent = nullptr) : QMainWindow(parent)
    {
        // 在关闭事件中弹出提示窗口
        connect(this, &QMainWindow::closeEvent, this, &MainWindow::closeEvent);

        // 设置主窗口属性,使得点击关闭按钮时不会直接退出应用程序
        setAttribute(Qt::WA_DeleteOnClose);
    }

protected:
    void closeEvent(QCloseEvent *event) override
    {
        // 弹出提示窗口
        QMessageBox::StandardButton resBtn = QMessageBox::question(this, "提示", "确定要退出吗?",
                                                                   QMessageBox::Yes | QMessageBox::No,
                                                                   QMessageBox::No);

        // 判断点击的按钮
        if (resBtn == QMessageBox::Yes) {
            // 点击了OK按钮,退出应用程序
            qApp->quit();
        } else {
            // 点击了其他按钮,取消关闭事件
            event->ignore();
        }
    }
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    MainWindow w;
    w.show();

    return a.exec();
}

在上述示例代码中,我们创建了一个MainWindow类继承自QMainWindow,并在其构造函数中连接了关闭事件的信号与槽函数。在槽函数中,我们使用QMessageBox来弹出提示窗口,并根据点击的按钮来决定是否退出应用程序。

另外,我们还需要在main函数中创建MainWindow对象并显示出来。

注意:为了使得点击关闭按钮时不会直接退出应用程序,我们在MainWindow的构造函数中设置了setAttribute(Qt::WA_DeleteOnClose)。这样,在关闭窗口时会自动调用delete,从而删除MainWindow对象。

Qt点击关闭按钮弹出提示窗口点击OK退出

原文地址: https://www.cveoy.top/t/topic/ixdg 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录