// ui_frameless_dialog.h
#pragma once
#include <QWidget>
#include <QMouseEvent>
class FramelessDialog : public QWidget {
Q_OBJECT
public:
FramelessDialog(QWidget* parent = Q_NULLPTR);
void SetSize(int32_t width, int32_t height, int32_t parent_width, int32_t parent_height);
private:
void mousePressEvent(QMouseEvent* event) override;
protected:
QWidget* dialog_;
};
// ui_frameless_dialog.cpp
#include "ui_frameless_dialog.h"
FramelessDialog::FramelessDialog(QWidget* parent) : QWidget(parent), m_pDialog(new QWidget(this)) {
setAttribute(Qt::WA_StyledBackground, true);
dialog_->setAttribute(Qt::WA_StyledBackground, true);
}
void FramelessDialog::SetSize(int32_t width, int32_t height, int32_t parent_width, int32_t parent_height) {
resize(parent_width, parent_height);
//对话框后面加深
setStyleSheet("background:rgb(0,0,0,50%);");
int32_t delta_x = (width() - width) >> 1;
int32_t delta_y = (height() - height) / 3;
dialog_->setGeometry(delta_x, delta_y, width, height);
}
void FramelessDialog::mousePressEvent(QMouseEvent* event) {
//点击对话框外侧关闭
int32_t pos_x = event->x(), pos_y = event->y();
if (pos_x < m_pDialog->x() || pos_y < m_pDialog->y() || pos_x > m_pDialog->x() + m_pDialog->width() ||
pos_y > m_pDialog->y() + m_pDialog->height()) {
hide();
}
}