一.蒙层的作用
1.为了其他窗口不被误操作,禁止对其他窗口操作
二.应用场景
1.一些触摸屏设备上弹出一个dialog窗口,在操作这个窗口的时候不希望后面的窗口被误操作
2.之前做一个医疗设备就曾有过这种需求,因为医疗设备对安全性要求非常高,是绝对不允许误触的
三.代码实现
1.mask.h
#include <QWidget>
class MaskWidget : public QWidget
{
Q_OBJECT
public:
static MaskWidget *Instance();
explicit MaskWidget(QWidget *parent = 0);
protected:
void showEvent(QShowEvent *);
bool eventFilter(QObject *obj, QEvent *event);
private:
static QScopedPointer<MaskWidget> self;
QWidget *mainWidget;
QStringList dialogNames;
public Q_SLOTS:
void setMainWidget(QWidget *mainWidget);
void setDialogNames(const QStringList &dialogNames);
void setBgColor(const QColor &bgColor);
void setOpacity(double opacity);
};
#endif // MASKWIDGET_H
2.mask.cpp
QScopedPointer<MaskWidget> MaskWidget::self;
MaskWidget *MaskWidget::Instance()
{
if (self.isNull()) {
static QMutex mutex;
QMutexLocker locker(&mutex);
if (self.isNull()) {
self.reset(new MaskWidget);
}
}
return self.data();
}
MaskWidget::MaskWidget(QWidget *parent) : QWidget(parent)
{
mainWidget = 0;
setOpacity(0.7);
setBgColor(QColor(0, 0, 0));
this->setGeometry(deskGeometry);
this->setWindowFlags(Qt::FramelessWindowHint | Qt::Tool);
qApp->installEventFilter(this);
}
void MaskWidget::setMainWidget(QWidget *mainWidget)
{
if (this->mainWidget != mainWidget) {
this->mainWidget = mainWidget;
}
}
void MaskWidget::setDialogNames(const QStringList &dialogNames)
{
if (this->dialogNames != dialogNames) {
this->dialogNames = dialogNames;
}
}
void MaskWidget::setOpacity(double opacity)
{
this->setWindowOpacity(opacity);
}
void MaskWidget::setBgColor(const QColor &bgColor)
{
QPalette palette = this->palette();
palette.setBrush(QPalette::Window, bgColor);
this->setPalette(palette);
}
void MaskWidget::showEvent(QShowEvent *)
{
if (mainWidget) {
this->setGeometry(mainWidget->geometry());
}
}
bool MaskWidget::eventFilter(QObject *obj, QEvent *event)
{
int type = event->type();
if (type == QEvent::Show) {
if (dialogNames.contains(obj->objectName())) {
this->show();
this->activateWindow();
QWidget *w = (QWidget *)obj;
w->activateWindow();
}
} else if (type == QEvent::Hide) {
if (dialogNames.contains(obj->objectName())) {
this->hide();
}
} else if (type == QEvent::WindowActivate) {
if (mainWidget) {
if (obj->objectName() == mainWidget->objectName()) {
if (this->isVisible()) {
this->activateWindow();
}
}
}
}
return QObject::eventFilter(obj, event);
}
3.widget.cpp
frmMaskWidget::frmMaskWidget(QWidget *parent) : QWidget(parent), ui(new Ui::frmMaskWidget)
{
ui->setupUi(this);
initForm();
}
frmMaskWidget::~frmMaskWidget()
{
delete ui;
}
void frmMaskWidget::initForm()
{
MaskWidget::Instance()->setMainWidget(this->topLevelWidget());
MaskWidget::Instance()->setDialogNames(QStringList() << "frmTest1");
}
void frmMaskWidget::on_pushButton_clicked()
{
QDialog d;
d.setObjectName("frmTest1");
d.setWindowTitle("弹出窗体");
d.resize(400, 300);
d.exec();
}
void frmMaskWidget::on_pushButton_2_clicked()
{
ui->pushButton_2->setText("AAA");
}
四.结果展示