Qt之setMask()
前言
使用遮罩可以将窗口形状多样化,变成各种各样的图片或者图形,先看一下效果吧👇
可以看到现在的窗口是一束花,而我们拖动花就相当于拖动窗口,
setMask()只是说可以让哪些地方可见哪些地方不可见其实方形窗口一直都有在,只是让我们只看得到花的部分,下面就是不加setMask()时的窗口样子,这样是不是更明白了呢!!
注意:setMask有几种方式,其中就是像我这样的void QWidget::setMask(const QBitmap &bitmap),还有一种是void QWidget::setMask(const QRegion ®ion),第二种是指定一个区域可见,异曲同工,只是说我们是将图片传进去(图片必须是背景透明)让不透明的地方可见,而另外一种方式是指定一个区域(坐标及大小)可见。
如果哪个区域可见,那么这个区域才可以接收到鼠标信号哦!!
代码实现
widget.h
#ifndef WIDGET_H
#define WIDGET_H#include <QWidget>
#include <QPoint>
#include <QMouseEvent>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACEclass Widget : public QWidget
{Q_OBJECTpublic:Widget(QWidget *parent = nullptr);~Widget();
protected:void paintEvent(QPaintEvent *event) override;void mousePressEvent(QMouseEvent*event)override;void mouseMoveEvent(QMouseEvent*event)override;void mouseReleaseEvent(QMouseEvent*event)override;
private:Ui::Widget *ui;bool m_isPressed;QPoint m_mousePoint;
};
#endif // WIDGET_H
widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include <QPixmap>
#include <QBitmap>
#include <QPainter>
Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget)
{ui->setupUi(this);QPixmap pixmap;pixmap.load(":/flower.png");resize(pixmap.size());//窗口设置遮罩setMask(pixmap.mask());m_isPressed = false;
}Widget::~Widget()
{delete ui;
}void Widget::paintEvent(QPaintEvent *event)
{QPainter painter(this);painter.drawPixmap(0,0,QPixmap(":/flower.png"));
}void Widget::mousePressEvent(QMouseEvent *event)
{m_isPressed = true;m_mousePoint = event->globalPos()-pos();QWidget::mousePressEvent(event);}void Widget::mouseMoveEvent(QMouseEvent *event)
{//只有左键才可以拖动if(m_isPressed==true&&event->buttons()&Qt::LeftButton){move(event->globalPos()-m_mousePoint);m_mousePoint = event->globalPos()-pos();QWidget::mouseMoveEvent(event);}
}void Widget::mouseReleaseEvent(QMouseEvent *event)
{m_isPressed = false;m_mousePoint = event->globalPos()-pos();
}
最关键的地方就是
QPixmap pixmap;pixmap.load(":/flower.png");resize(pixmap.size());//窗口设置遮罩setMask(pixmap.mask());
以及重绘事件
void Widget::paintEvent(QPaintEvent *event)
{QPainter painter(this);painter.drawPixmap(0,0,QPixmap(":/flower.png"));
}