Qt透明无边框窗口的实现示例分享!

最近在封装一些类的时候,打算做一个窗口框架,能实现拖动、无边框、透明基本样式等功能

Qt透明无边框窗口的实现示例

0x00 如何透明窗口?

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

  setWindowFlags(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 如何无边框窗口?

设置setWindowFlags(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);      setWindowFlags(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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持<计算机技术网(www.ctvol.com)!!>。

—-想了解Qt透明无边框窗口的实现示例分享!全部内容且更多的C语言教程关注<计算机技术网(www.ctvol.com)!!>

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/c-cdevelopment/483299.html

(0)
上一篇 2020年11月9日
下一篇 2020年11月9日

精彩推荐