Qt无框窗口

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;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值