【问题标题】:Qt Dialog X Button Override Reject Not Working As ExpectedQt Dialog X Button Override Reject 未按预期工作
【发布时间】:2016-05-11 20:35:00
【问题描述】:

当用户点击典型的关闭按钮(通常在最小化按钮旁边带有 X 的那个)时,我一直试图隐藏一个独立的对话框应用程序。我看到了这篇文章:

Qt: How do I handle the event of the user pressing the 'X' (close) button?

我认为这会有我的解决方案,但是当我实施它时会出现奇怪的行为。

void MyDialog::reject()
{
    this->hide()
}

当我点击 X 按钮时,整个应用程序将关闭(进程消失),这不是我想要的。由于我的 gui 是通过命令行生成的,因此我设置了一个测试系统,在其中我可以通过一个文本命令告诉我的对话框隐藏,在该命令中我调用相同的 'this->hide()' 指令,并且一切正常。对话框隐藏,然后在我告诉它显示时重新显示。

任何想法为什么即使我没有明确告诉拒绝方法也会完全关闭我的应用程序?

【问题讨论】:

  • 当您关闭对话框时,应用程序的任何其他窗口是否可见?

标签: c++ qt


【解决方案1】:

在你的对话框类中重写虚函数“virtual void closeEvent(QCloseEvent * e)”。代码注释会详细解释。

Dialog::Dialog(QWidget *parent) :QDialog(parent), ui(new Ui::Dialog){
    ui->setupUi(this);
}
Dialog::~Dialog(){
    delete ui;
}
//SLOT
void Dialog::fnShow(){
    //Show the dialog
    this->show();
}
void Dialog::closeEvent(QCloseEvent *e){
    QMessageBox::StandardButton resBtn = QMessageBox::question( this, "APP_NAME",
                                         tr("Are you sure?\n"),
                                         QMessageBox::Cancel | QMessageBox::No | QMessageBox::Yes,
                                         QMessageBox::Yes);

    if (resBtn != QMessageBox::Yes){
        //Hiding the dialog when the close button clicked
        this->hide();
        //event ignored
        e->ignore();
        //Testing. To show the dialog again after 2 seconds
        QTimer *qtimer = new QTimer(this);
        qtimer->singleShot(2000,this,SLOT(fnShow()));
        qtimer->deleteLater();
    }
    //below code is for understanding
    //as by default it is e->accept();
    else{
        //close forever 
        e->accept();
    }
}

【讨论】:

  • 我之前遇到过这个问题,当我在 QDialog 上实现它时,只是使用 e->ignore() 行进行快速测试,我的对话框停止响应点击 X。让我重试它并仔细检查。
  • 不管出于什么原因,现在这对我有用。感谢您的帮助!
猜你喜欢
  • 2021-11-28
  • 2020-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-04
  • 2022-01-24
  • 2015-05-11
相关资源
最近更新 更多