1、在mainwindow中重写closeEvent
void closeEvent(QCloseEvent *event);
2、在cpp中实现
QDialog* log = new QDialog(this); log->setObjectName("log"); log->setStyleSheet("#log{background:#3379B7;}"); log->deleteLater(); log->setWindowTitle("退出平台"); QRect clientRect = QApplication::desktop()->availableGeometry(); log->setGeometry(clientRect.width()/2,clientRect.height()/2,200,100); QLabel* lel = new QLabel(log); lel->setText("确定退出平台吗?"); lel->setStyleSheet("QLabel{font-family:'宋体';font-size:20px;color:white;}"); lel->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter); QPushButton* okBtn = new QPushButton(log); QPushButton* clsBtn = new QPushButton(log); okBtn->setText("确定"); clsBtn->setText("取消"); okBtn->setMaximumWidth(100); clsBtn->setMaximumWidth(100); QObject::connect(okBtn,&QPushButton::clicked,[=]() { log->done(RET_OK); }); QObject::connect(clsBtn,&QPushButton::clicked,[=]() { log->done(RET_ERR); }); QHBoxLayout* hLayout = new QHBoxLayout(); hLayout->setSpacing(5); hLayout->addStretch(); hLayout->addWidget(okBtn); hLayout->addWidget(clsBtn); QVBoxLayout* v = new QVBoxLayout(); v->addWidget(lel); v->addItem(hLayout); log->setLayout(v); if(RET_OK==log->exec()) { event->accept(); } else { event->ignore(); }
3、关闭窗口或者主动调用this->close()函数就会触发closeEvent