如何自定义控件

新建类

#include "light.h"
#include <QPainter>
#include <QMouseEvent>
#include <QDebug>
light::light(QWidget *parent) : QWidget(parent)
{
}



void light::paintEvent(QPaintEvent *) {
    QPainter painter(this);
    painter.translate(width() / 2, height() / 2);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setPen(Qt::transparent);






    int radius = 20;



    // 外边框
    QLinearGradient lg1(0, -radius, 0, radius);
    lg1.setColorAt(0, QColor(255, 255, 255));
    lg1.setColorAt(1, QColor(166, 166, 166));
    painter.setBrush(lg1);
    painter.drawEllipse(-radius, -radius, radius << 1, radius << 1);

    // 内边框
    radius -= 8;
    QLinearGradient lg2(0, -radius, 0, radius);
    lg2.setColorAt(0, QColor(166, 166, 166));
    lg2.setColorAt(1, QColor(255, 255, 255));
    painter.setBrush(lg2);
    painter.drawEllipse(-radius, -radius, radius << 1, radius << 1);

    radius -= 4;
    if(i==1){

        QRadialGradient rg(0, 0, radius);
        rg.setColorAt(0, QColor(245, 0, 0));
        rg.setColorAt(0.6, QColor(210, 0, 0));
        rg.setColorAt(1, QColor(166, 0, 0));
        painter.setBrush(rg);
        painter.drawEllipse(-radius, -radius, radius << 1, radius << 1);
        qDebug()<<"---1--------";

    }
    if(i==0){

        QRadialGradient rg(0, 0, radius);
        rg.setColorAt(0, QColor(0, 0, 0));
        rg.setColorAt(0.6, QColor(0, 0, 0));
        rg.setColorAt(1, QColor(0, 0, 0));
        painter.setBrush(rg);
        painter.drawEllipse(-radius, -radius, radius << 1, radius << 1);
        qDebug()<<"---2--------";

    }

    QPainterPath path;
    path.addEllipse(-radius, -radius, radius << 1, radius << 1);
    QPainterPath bigEllipse;

    radius *= 2;
    bigEllipse.addEllipse(-radius, -radius + 140, radius << 1, radius << 1);
    path -= bigEllipse;

    QLinearGradient lg3(0, -radius, 0, radius);
    lg3.setColorAt(0, QColor(255, 200, 200, 180));
    lg3.setColorAt(1, QColor(255, 200, 200, 100));
    painter.setBrush(lg3);
    painter.drawPath(path);
}


// 鼠标按下事件
void light::mousePressEvent(QMouseEvent *event)
{
    if (isEnabled()) {
        if (event->buttons() & Qt::LeftButton) {
            event->accept();
            i = ~i;
//必须要加更新,才会重绘窗口,使用repaint()或者update()
            update();
            qDebug()<<"anxia";
        } else {
            event->ignore();
        }
    }
}





#ifndef LIGHT_H
#define LIGHT_H

#include <QWidget>

class light : public QWidget
{
    Q_OBJECT
public:
    explicit light(QWidget *parent = nullptr);
    void paintEvent(QPaintEvent *);
    void mousePressEvent(QMouseEvent *event) Q_DECL_OVERRIDE;

    qint32 i=0;
signals:

public slots:
};

#endif // LIGHT_H

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值