一个控件,不知道怎么命名,可以作为按钮也可以用作指示灯

#ifndef WIDGET_H
#define WIDGET_H

#include 

QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE

class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QColor color,QWidget *parent = nullptr);
    ~Widget();
    void paintEvent(QPaintEvent *event);

private:
    Ui::Widget *ui;
    int radius{30};
    bool pressed{false};
    QColor color;

    // QWidget interface
protected:
    void mousePressEvent(QMouseEvent *event) override;
    void mouseReleaseEvent(QMouseEvent *event) override;
};
#endif // WIDGET_H
#include "widget.h"
#include "ui_widget.h"
#include 
#include 

Widget::Widget(QColor color, QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    this->color = color;
    ui->setupUi(this);
}

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

void Widget::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.setPen(Qt::transparent);
    painter.setRenderHint(QPainter::Antialiasing);

    auto rect = this->rect();
    painter.scale(rect.width()/1000.0, rect.height()/1000.0);

    auto radialGent = QRadialGradient(QPointF(0,0),qSqrt(2000000),QPointF(0, 0));//2000000 = 根号(1000² + 1000²)
    radialGent.setColorAt(0, QColor(224, 224, 224));
    radialGent.setColorAt(1, QColor(28, 28, 28));

    auto radius = this->radius * 1000.0 / (std::min(rect.width(),rect.height()));
    painter.setBrush(QBrush(radialGent));
    painter.drawRoundedRect(QRect(0,0,1000,1000).adjusted(2,2,-2,-2),radius,radius);

    radialGent = QRadialGradient(QPointF(1000, 1000), qSqrt(2000000), QPointF(1000, 1000));
    radialGent.setColorAt(0, QColor(224, 224, 224));
    radialGent.setColorAt(1, QColor(28, 28, 28));
    painter.setBrush(QBrush(radialGent));
    painter.drawRoundedRect(QRect(0,0,1000,1000).adjusted(100,100,-100,-100),radius,radius);

    painter.setBrush(color);
    painter.drawRoundedRect(QRect(0,0,1000,1000).adjusted(150,150,-150,-150),radius,radius);

    if(pressed)
    {
        QColor slightlyOpaqueBlack(0, 0, 0, 63);
        painter.setBrush(slightlyOpaqueBlack);
        painter.setPen(Qt::transparent);
        painter.drawRoundedRect(QRect(0,0,1000,1000).adjusted(150,150,-150,-150),radius,radius);
    }
}

void Widget::mousePressEvent(QMouseEvent *event)
{
    pressed = true;
    update();
}

void Widget::mouseReleaseEvent(QMouseEvent *event)
{
    pressed = false;
    update();
}
#include 
#include 

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    auto widget = new QWidget;
    auto hb = new QHBoxLayout(widget);
    hb->addWidget(new Widget(Qt::cyan));
    hb->addWidget(new Widget(Qt::magenta));
    hb->addWidget(new Widget(Qt::blue));
    hb->addWidget(new Widget(Qt::green));
    widget->show();
    widget->resize(600,400);
    return a.exec();
}

 一个控件,不知道怎么命名,可以作为按钮也可以用作指示灯_第1张图片

你可能感兴趣的:(#,Qt编写自定义控件,qt)