QWidget实现QDialog的exec()模态效果

scorlw 发布于

QWidget实现QDialog的exec()模态效果

要点

  1. setWindowModality(Qt::ApplicationModal);//设置Widget模态
  2. 使用 QEventLoop 实现事件循环;
  3. 重写 closeEvent ,退出事件循环;

实现

.h文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#ifndef PARASETWID_H
#define PARASETWID_H

#include <QWidget>
#include <QEventLoop>
#include <QCloseEvent>

namespace Ui {
class ParaSetWid;
}

class ParaSetWid : public QWidget
{
Q_OBJECT

public:
explicit ParaSetWid(QWidget *parent = 0);
~ParaSetWid();

int exec();

private:
Ui::ParaSetWid *ui;

int m_Result;
QEventLoop *m_Loop;

protected:
void closeEvent(QCloseEvent *event);
private slots:
void on_OKBtn_clicked();
void on_CanBtn_clicked();
};

#endif // PARASETWID_H

.cpp文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include "parasetwid.h"
#include "ui_parasetwid.h"

ParaSetWid::ParaSetWid(QWidget *parent) :
QWidget(parent),
ui(new Ui::ParaSetWid)
{
ui->setupUi(this);
setWindowModality(Qt::ApplicationModal);
}

ParaSetWid::~ParaSetWid()
{
delete ui;
}

int ParaSetWid::exec()
{
m_Result=-1;
this->show();
m_Loop=new QEventLoop(this);
m_Loop->exec();
return m_Result;
}

void ParaSetWid::closeEvent(QCloseEvent *event)
{
if(m_Loop!=NULL)
{
m_Loop->exit();
}
event->accept();
}

void ParaSetWid::on_OKBtn_clicked()
{
m_Result=1;
this->close();
}

void ParaSetWid::on_CanBtn_clicked()
{
m_Result=0;
this->close();
}