用qt写一个圆形的自定义按钮
时间: 2024-05-24 10:12:15 浏览: 175
Qt实现自定义按钮的状态
以下是用Qt编写圆形自定义按钮的示例代码:
circlebutton.h
```
#ifndef CIRCLEBUTTON_H
#define CIRCLEBUTTON_H
#include <QWidget>
#include <QPainter>
#include <QMouseEvent>
class CircleButton : public QWidget
{
Q_OBJECT
public:
explicit CircleButton(QWidget *parent = nullptr);
QSize sizeHint() const override;
protected:
void paintEvent(QPaintEvent *event) override;
void mousePressEvent(QMouseEvent *event) override;
void mouseReleaseEvent(QMouseEvent *event) override;
void enterEvent(QEvent *event) override;
void leaveEvent(QEvent *event) override;
signals:
void clicked();
private:
bool m_pressed;
};
#endif // CIRCLEBUTTON_H
```
circlebutton.cpp
```
#include "circlebutton.h"
CircleButton::CircleButton(QWidget *parent) : QWidget(parent), m_pressed(false)
{
setFixedSize(50, 50);
}
QSize CircleButton::sizeHint() const
{
return QSize(50, 50);
}
void CircleButton::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event);
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing, true);
QColor bgColor = m_pressed ? Qt::lightGray : Qt::white;
QColor borderColor = m_pressed ? Qt::gray : Qt::black;
QColor textColor = m_pressed ? Qt::white : Qt::black;
painter.setBrush(bgColor);
painter.setPen(borderColor);
painter.drawEllipse(rect().adjusted(1, 1, -1, -1));
painter.setPen(textColor);
painter.drawText(rect(), Qt::AlignCenter, "Button");
}
void CircleButton::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton)
{
m_pressed = true;
update();
}
}
void CircleButton::mouseReleaseEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton)
{
if (m_pressed)
{
m_pressed = false;
update();
emit clicked();
}
}
}
void CircleButton::enterEvent(QEvent *event)
{
Q_UNUSED(event);
setCursor(Qt::PointingHandCursor);
}
void CircleButton::leaveEvent(QEvent *event)
{
Q_UNUSED(event);
unsetCursor();
}
```
使用方法:
在需要使用圆形按钮的窗口中,添加以下代码:
```
CircleButton *button = new CircleButton(this);
connect(button, &CircleButton::clicked, [=](){
// 点击按钮后执行的代码
});
```
示例效果:
![circlebutton-demo.png](https://cdn.jsdelivr.net/gh/sheng962464/PicGo/img/20211018145638.png)
阅读全文