Qt自定义控件之圆形按钮、圆形头像

Qt自定义控件之圆形按钮、圆形头像

前言

现在很多软件的头像或者按钮都是圆形了,看起来比较舒服。比如QQ登录头像,酷狗客户端的一些按钮都是圆形。Qt实现圆形头像,大致有几种思路,第1种就是图片遮罩的方式,还有一种方法是使用样式表设置border-radius来实现圆形边框。这里要介绍的是使用Qt的绘画大师QPainter来实现。

代码实现

#include "roundbutton.h"
#include "ui_roundbutton.h"
#include <QPainter>

#ifndef NO_TOUCH_EVENT

RoundButton::RoundButton(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::RoundButton)
{
    
    
    ui->setupUi(this);

    m_radius = 200;
    isPressed = false;
    setIcon(":/ppd.jpeg");

#ifdef NO_TOUCH_EVENT
    connect(this,&RoundButton::btnClicked,[=]
    {
    
    
        qDebug("Round button clicked.");
        setIcon(":/timo.jpg");
    });
#endif
}

RoundButton::~RoundButton()
{
    
    
    delete ui;
}

void RoundButton::setIcon(const QString &fileName)
{
    
    
     if(pixmap.load(fileName))
     {
    
    
         qDebug("load icon ok.");
         update();
     }
}

void RoundButton::setRadius(int radius)
{
    
    
    m_radius = radius;
}

#ifdef NO_TOUCH_EVENT
void RoundButton::mousePressEvent(QMouseEvent *event)
{
    
    
    Q_UNUSED(event)

    isPressed = true;
}

void RoundButton::mouseMoveEvent(QMouseEvent *event)
{
    
    
    Q_UNUSED(event)

}

void RoundButton::mouseReleaseEvent(QMouseEvent *event)
{
    
    
    Q_UNUSED(event)

    if(isPressed)
    {
    
    
        isPressed = false;
        emit btnClicked();
    }
}
#endif

void RoundButton::paintEvent(QPaintEvent *event)
{
    
    
    Q_UNUSED(event)

    QPainter painter(this);
    //抗锯齿
    painter.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);
	//绘画路径
    QPainterPath path;
    path.addEllipse(this->rect().center(),m_radius,m_radius);
    painter.setClipPath(path);
	//绘图
    painter.drawPixmap(QRect(0,0,m_radius*2,m_radius*2),pixmap);

}

QPainterPath是一个图形构建块的对象,如矩形、椭圆、直线和曲线。构建块可以加入在封闭的子路径中,例如:矩形或椭圆形。一个封闭的路径同时存在开始点和结束点。或者作为未封闭的子路径独立存在,如:直线和曲线。
addEllipse在指定的边框矩形内创建椭圆,并将其作为闭合子路径添加到绘制路径。
椭圆由一条顺时针的曲线组成,在零度(3点钟位置)开始和结束。
在这里插入图片描述
最后通过drawPixmap把图片画出来。本示例中打开 NO_TOUCH_EVENT 宏可作为圆形按钮使用,关闭就仅作为圆形头像使用。

当然了还可以使用painter的drawRoundedRect来实现圆形的绘画。这个有兴趣的可以自行研究。

实验效果

在这里插入图片描述
本示例代码稍作修改即可运用到工程中,灵活性也比较高。

作者:费码程序猿
欢迎技术交流:QQ:255895056
转载请注明出处,如有不当欢迎指正

猜你喜欢

转载自blog.csdn.net/haohaohaihuai/article/details/106502572