qt怎么实现捕获用户界面发送给对方_Qt透明无边框窗口

a74a16c1dec1138a8f3017ccda6e1478.png
文章介绍如何设置窗口透明,无边框和拖动。

3082502c137dd942da46a3b76803ffc7.gif

0x00 如何透明窗口?

第一步:开启窗口的透明层。

setWindowFlag(Qt::FramelessWindowHint); /* 注意:如果单纯开启窗口透明层效果,在Windows系统中必须设置, 其他系统可忽略。*/
setAttribute(Qt::WA_TranslucentBackground);

第二步: 重写paintEvent事件并使用QPainter画透明层。

void paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    /* 0x20为透明层颜色,可自定义设置为0x0到0xff */
    painter.fillRect(this->rect(), QColor(0, 0, 0, 0x20)); 
}

0x01 如何无边框窗口?

设置setWindowFlag(Qt::FramelessWindowHint)即可无边框窗口,但无法移动和改变大小。

0x02 如何拖拽窗口?

由于系统窗口被设置为Qt::FramelessWindowHint会导致窗口不能被拖动。通过捕获鼠标移动事件从而实现窗口移动。

void mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
    	/* 捕获按下时坐标 */
        m_startPoint = frameGeometry().topLeft() - event->globalPos();
    }
}

void mouseMoveEvent(QMouseEvent *event)
{
    /* 移动窗口 */
    this->move(event->globalPos() + m_startPoint);
}

0x03 完整代码

#include <QWidget>
#include <QVBoxLayout>
#include <QPushButton>
#include <QPainter>
#include <QMouseEvent>

class TransparentWidget : public QWidget
{
    Q_OBJECT
public:
    TransparentWidget(QWidget *parent = 0)
        : QWidget(parent)
    {
        setWindowTitle(QString::fromLocal8Bit("透明无边框窗口"));
        setFixedSize(480, 320);
        setWindowFlag(Qt::FramelessWindowHint);
        setAttribute(Qt::WA_TranslucentBackground);

        QPushButton *button = new QPushButton("Hello world!", this);
        button->setGeometry(5, 5, 80, 40);
    }

    void paintEvent(QPaintEvent *)
    {
        QPainter painter(this);
        painter.fillRect(this->rect(), QColor(0, 0, 0, 0x20)); /* 设置透明颜色 */
    }

    void mousePressEvent(QMouseEvent *event)
    {
        if (event->button() == Qt::LeftButton) {
            m_startPoint = frameGeometry().topLeft() - event->globalPos();
        }
    }

    void mouseMoveEvent(QMouseEvent *event)
    {
        this->move(event->globalPos() + m_startPoint);
    }

private:
    QPoint m_startPoint;
};

0x04 源码地址

https://github.com/aeagean/QtCustomWidget.git

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值