QT实现不规则窗体
扫描二维码
随时随地手机看文章
看到网上有很多不规则窗体的实现,效果很酷.于是使用QT也实现了一个,QT的不规则窗体实现非常简单,只需要设置一个mask(遮掩)图片,这个图片的格式可以使用png或bmp格式,我使用了png格式,默认窗体是矩形的,使用png图像,将需要隔离在窗体之外的区域的像素设置为白色或透明色,其他颜色的区域对应显示出来的窗体.关键代码就几行.
#ifndef IRREGULARFORM_H
#define IRREGULARFORM_H
#include
#include "ui_irregularform.h"
#include
#include
#include
#include
class IrregularForm : public QWidget
{
Q_OBJECT
public:
IrregularForm(QWidget *parent = 0);
~IrregularForm();
protected:
void mouseMoveEvent(QMouseEvent *event);
void mousePressEvent(QMouseEvent *event);
void mouseReleaseEvent(QMouseEvent *event);
private:
Ui::IrregularFormClass ui;
QPoint mouseMovePos;
};
#endif // IRREGULARFORM_H
#include "irregularform.h"
IrregularForm::IrregularForm(QWidget *parent)
: QWidget(parent)
{
setWindowFlags(Qt::FramelessWindowHint);
QPixmap mask(":/IrregularForm/Resources/mask.png");//加载掩码图像
setMask(QBitmap(mask.mask())); //设置窗体的掩码图像,抠除图像的白色区域实现不规则窗体
QPalette p;//设置调色板
p.setBrush(QPalette::Window, QBrush(mask));//将调色板的画刷设置为掩码位图,在不规则窗体上显示出掩码位图
setPalette(p);
mouseMovePos = QPoint(0, 0);
}
IrregularForm::~IrregularForm()
{
}
void IrregularForm::mouseMoveEvent(QMouseEvent *event)//鼠标按下并移动则移动不规则窗体
{
if(mouseMovePos != QPoint(0, 0))
{
move(geometry().x() + event->globalPos().x() - mouseMovePos.x(), geometry().y() + event->globalPos().y() - mouseMovePos.y());
mouseMovePos = event->globalPos();
}
}
void IrregularForm::mousePressEvent(QMouseEvent *event)
{
mouseMovePos = event->globalPos();
}
void IrregularForm::mouseReleaseEvent(QMouseEvent *event)
{
mouseMovePos = QPoint(0, 0);
}
效果图