Qt无框窗口
Qt::FramelessWindowHint 设置无框
QSizeGrip 控制调整大小
#include <QMouseEvent>
#include <QSizeGrip>
#include <QWidget>
//右下角改变窗口大小图标
class SizeGrip : public QSizeGrip
{
Q_OBJECT
public:
SizeGrip(QWidget* parent = nullptr) : QSizeGrip{parent}, m_pParent{parent} { setFixedSize(10, 10); }
private:
void mousePressEvent(QMouseEvent* event) override {
if (Qt::LeftButton == event->button()) { mStartPos = event->pos(); }
}
void mouseMoveEvent(QMouseEvent* event) override {
auto offset = event->pos() - mStartPos;
m_pParent->resize(m_pParent->size().width() + offset.x(), m_pParent->size().height() + offset.y());
}
private:
QPoint mStartPos;
QWidget* m_pParent;
};
//无边框窗口
class FramelessWidget : public QWidget
{
Q_OBJECT
public:
explicit FramelessWidget(const QString title = "标题", QWidget* parent = nullptr)
: QWidget{parent}
, mSizeGrip{new SizeGrip(this)} {
setWindowFlag(Qt::FramelessWindowHint);
setAttribute(Qt::WA_TranslucentBackground);
QIcon icon = QApplication::style()->standardIcon(QStyle::SP_TabCloseButton);
connect(btnClose, &QPushButton::clicked, this, &FramelessWidget::close);
mTLabel = new QLabel(title, this);
mTLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
mTLabel->setStyleSheet("padding-left:6px;color:white;"
"background-color:rgba(0,0,100,180);"
"border-top-left-radius:8;"
"border-top-right-radius:8");
btnClose = new QPushButton(icon, "", this);
btnClose->setFixedSize(iconSize, iconSize);
btnClose->raise();
setMinimumSize(50, 50);
resize(300, 200);
}
protected:
void paintEvent(QPaintEvent* e) override {
QPainter p(this);
p.setRenderHint(QPainter::Antialiasing);
p.setPen(Qt::NoPen);
p.setBrush(QColor(200, 200, 200, 100));
p.drawRoundedRect(rect(), 8, 8);
}
void resizeEvent(QResizeEvent* event) override {
mTLabel->setGeometry(0, 0, width(), 26);
btnClose->move(width() - 20, (iconSize >> 2));
mSizeGrip->move(width() - mSizeGrip->width(), height() - mSizeGrip->height());
}
void mousePressEvent(QMouseEvent* event) override {
if (Qt::LeftButton == event->button()) { mStartPos = event->pos(); }
}
void mouseMoveEvent(QMouseEvent* event) override {
if (event->buttons() & Qt::LeftButton) { move(event->pos() + pos() - mStartPos); }
}
private:
int iconSize{16};
QPoint mStartPos;
SizeGrip* mSizeGrip;
QPushButton* btnClose;
QLabel* mTLabel;
};