雷火电竞-中国电竞赛事及体育赛事平台

歡迎來到入門教程網(wǎng)!

C語言

當(dāng)前位置:主頁 > 軟件編程 > C語言 >

Qt透明無邊框窗口的實(shí)現(xiàn)示例

來源:本站原創(chuàng)|時(shí)間:2020-01-10|欄目:C語言|點(diǎn)擊:

最近在封裝一些類的時(shí)候,打算做一個(gè)窗口框架,能實(shí)現(xiàn)拖動(dòng)、無邊框、透明基本樣式等功能

0x00 如何透明窗口?

第一步:開啟窗口的透明層。

setWindowFlags(Qt::FramelessWindowHint); /* 注意:如果單純開啟窗口透明層效果,在Windows系統(tǒng)中必須設(shè)置, 其他系統(tǒng)可忽略。 */
setAttribute(Qt::WA_TranslucentBackground);

第二步: 重寫paintEvent事件并使用QPainter畫透明層。

void paintEvent(QPaintEvent *)
{
  QPainter painter(this);
  /* 0x20為透明層顏色,可自定義設(shè)置為0x0到0xff */
  painter.fillRect(this->rect(), QColor(0, 0, 0, 0x20)); 
}

0x01 如何無邊框窗口?

設(shè)置setWindowFlags(Qt::FramelessWindowHint);即可無邊框窗口,但無法移動(dòng)和改變大小。

0x02 如何拖拽窗口?

由于系統(tǒng)窗口被設(shè)置為Qt::FramelessWindowHint會(huì)導(dǎo)致窗口不能被拖動(dòng)。通過捕獲鼠標(biāo)移動(dòng)事件從而實(shí)現(xiàn)窗口移動(dòng)。

void mousePressEvent(QMouseEvent *event)
{
  if (event->button() == Qt::LeftButton) {
    /* 捕獲按下時(shí)坐標(biāo) */
    m_startPoint = frameGeometry().topLeft() - event->globalPos();
  }
}

void mouseMoveEvent(QMouseEvent *event)
{
  /* 移動(dòng)窗口 */
  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)); /* 設(shè)置透明顏色 */
  }

  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

以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持我們。

上一篇:C語言實(shí)現(xiàn)點(diǎn)餐系統(tǒng)

欄    目:C語言

下一篇:基于C語言實(shí)現(xiàn)點(diǎn)菜系統(tǒng)

本文標(biāo)題:Qt透明無邊框窗口的實(shí)現(xiàn)示例

本文地址:http://www.jygsgssxh.com/a1/Cyuyan/122.html

網(wǎng)頁制作CMS教程網(wǎng)絡(luò)編程軟件編程腳本語言數(shù)據(jù)庫服務(wù)器

如果侵犯了您的權(quán)利,請(qǐng)與我們聯(lián)系,我們將在24小時(shí)內(nèi)進(jìn)行處理、任何非本站因素導(dǎo)致的法律后果,本站均不負(fù)任何責(zé)任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權(quán)所有