要点
1. setWindowModality(Qt::ApplicationModal);//设置Widget模态
2. 使用 QEventLoop 实现事件循环;
3. 重写 closeEvent ,退出事件循环;
实现
//.h
public:
int exec();
private:
QPushButton *m_BtnOK;
QPushButton *m_BtnCancel;
int m_Result;
QEventLoop *m_Loop;
protected:
void closeEvent(QCloseEvent *event);
public slots:
void btnOKSlot();
void btnCancelSlot();
//.cpp
this->setWindowModality(Qt::ApplicationModal);
void MessageBox::btnOKSlot()
{
m_Result=1;
this->close();
}
void MessageBox::btnCancelSlot()
{
m_Result=0;
this->close();
}
int MessageBox::exec()
{
m_Result=-1;
this->show();
m_Loop=new QEventLoop(this);
m_Loop->exec();
return m_Result;
}
void MessageBox::closeEvent(QCloseEvent *event)
{
if(m_Loop!=NULL)
{
m_Loop->exit();
}
event->accept();
}
评论区