Qt 实现遮罩效果弹框
思路:底层画一个透明的遮罩矩形,中间放置一些控件。
步骤:1.设置窗口背景透明属性
2.重写paintEvent函数,遮罩背景就是画一个弹框大小的矩形,并设置颜色和透明度
3.然后在遮罩框上添加其他的控件
ExitWidget::ExitWidget(QWidget* parent) : QWidget(parent) { setWindowFlags(Qt::FramelessWindowHint | Qt::Tool); setAttribute(Qt::WA_TranslucentBackground); } void ExitWidget::paintEvent(QPaintEvent* event) { QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing); //反走样 painter.setClipping(true);
//遮罩 painter.setPen(Qt::NoPen); painter.setBrush(QColor(0, 0, 0, 120)); painter.drawRect(rect());
//窗口外框 QRect rectButtom((width() - Width) / 2, (height() - Height) / 2, Width, Height); painter.setPen(Qt::NoPen); painter.setBrush(QColor(255, 255, 255, 120)); painter.drawRoundedRect(rectButtom, border, border); //画圆角矩形 QPixmap pix; pix.load(":/act/exit/MaskGroup.png"); //添加图片(从而形成了【不规则窗体】) pix = pix.scaled(413, 203); painter.drawPixmap((width() - pix.width()) / 2, rectButtom.y() - 120, pix);int spacing = (Width - m_pCancelButton->width() * 2) / 3; m_pCancelButton->move(rectButtom.x() + spacing, m_pTipLabel->y() + m_pTipLabel->height() + 20); m_pOkButton->move(m_pCancelButton->x() + m_pCancelButton->width() + spacing, m_pCancelButton->y()); }
//设置该窗口的位置(注意:当父窗口大小改变、移动、最小化后恢复都得设置位置)
QPoint globalPos = this->mapToGlobal(QPoint(0, 0)); //父窗口绝对坐标
m_pExitWidget->move(globalPos.x(), globalPos.y()); //窗口移动