【问题标题】:How to close only subwindow when use closeEvent for X button?将closeEvent用于X按钮时如何仅关闭子窗口?
【发布时间】:2016-08-25 19:11:33
【问题描述】:

界面右上角的X按钮我使用closeEvent方法。

要求是:

  • 当我单击“关闭”时 -> 两个窗口(退出和主窗口)都将关闭。
  • 当我点击“取消”-> 只有“退出”窗口会被关闭时,MainWindow 仍然停留在那里。

但是当我点击“取消”时,两个窗口都关闭了 -> 如何解决这个问题?

如何在“保存”和“关闭”之间移动“取消”按钮

这是我的代码

myclass.h

class MyClass : public QWidget
{
    Q_OBJECT

public:
    MyClass(QcgDatabase* db, int hostid, QWidget *parent = 0);
    ~MyClass();

public slots:
    void save_clicked();

private:
    Ui::MyClass ui;
    QMessageBox* dialog = NULL;
    void closeEvent(QCloseEvent *bar);
};

myclass.cpp

MyClass::MyClass(QcgDatabase * db, int hostid, QWidget *parent)
: QWidget(parent)
{
    ui.setupUi(this);
    .......
    .......
}

void MyClass::closeEvent(QCloseEvent *bar)
{
    if (!dialog) {
        dialog = new QMessageBox(this);
    }
    dialog->setWindowModality(Qt::WindowModal);
    dialog->setWindowTitle(QLatin1String("Exit"));
    dialog->setText(QLatin1String("You have not saved data. Click \"Close\" to close the data table."));
    dialog->setStandardButtons(QMessageBox::Save | QMessageBox::Cancel | QMessageBox::Close);

    int result = dialog->exec();
    if (result == QMessageBox::Save) {
        save_clicked();
    }
    else if (result == QMessageBox::Cancel) {
        dialog->close();
        return;
    }
    else if (result == QMessageBox::Close) {
        dialog->close();
    }

    bar->accept();
}

编辑:

好的,我修复了窗口的问题:

 else if (result == QMessageBox::Cancel) {
    bar->ignore();
    return;
 }

请帮我交换“关闭”和“取消”按钮的位置!

【问题讨论】:

    标签: c++ qt function


    【解决方案1】:

    在您的if (result == QMessageBox::Cancel) 分支中,仅关闭您的对话框是不够的。您还需要在事件对象上调用QEvent::ignore()

    bar->ignore()
    

    这是因为你的MyClass::closeEvent 被调用只是为了让你有机会在窗口即将关闭时做某事,但事件本身将在 Qt 框架的迷宫中继续它的旅程,最终会导致窗口关闭 -除非您将其标记为忽略

    【讨论】:

    • 谢谢,我也同时找到了。你能帮我调换“关闭”和“取消”的位置吗?
    • 我担心使用StandardButtons 是不可能的,您需要自己设计对话框,将按钮一一放置到所需位置
    • 谢谢,是的,也许我需要设计一个新对话框。我有一个简单的解决方案dialog->setButtonText(QMessageBox::Close,"Cancel"); dialog->setButtonText(QMessageBox::Cancel,"Close"); 但它看起来很奇怪))))
    • 顺便说一句,从 UI 设计的角度来看,我认为交换“关闭”和“取消”的位置不是一个好主意 - 你会破坏标准按钮布局的现有一致性
    • 是的,经过讨论,我决定将其保留为标准。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2014-11-11
    • 1970-01-01
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多