qt 自定义旋钮实现三个挡位的功能不使用QDial
时间: 2023-12-22 12:03:05 浏览: 94
qt 自定义控件
5星 · 资源好评率100%
如果您不想使用QDial控件,也可以使用QPainter和QMouseEvent来实现自定义旋钮并实现三个挡位的功能。以下是一个示例实现:
```
class CustomKnob : public QWidget
{
public:
CustomKnob(QWidget *parent = nullptr) : QWidget(parent)
{
setFixedSize(100, 100);
m_value = 0;
m_notches = 3;
}
void paintEvent(QPaintEvent *event) override
{
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing, true);
// 绘制背景圆形
painter.setPen(Qt::NoPen);
painter.setBrush(QColor("#dcdcdc"));
painter.drawEllipse(rect().center(), 40, 40);
// 绘制指针
painter.setBrush(QColor("#ff7f50"));
painter.save();
painter.translate(rect().center());
painter.rotate(m_value * 360 / 100.0);
painter.drawConvexPolygon(QPolygonF(QVector<QPointF>() << QPointF(-20, 0) << QPointF(0, -50) << QPointF(20, 0)));
painter.restore();
// 绘制挡位
painter.setPen(QPen(QColor("#ff7f50"), 3));
qreal step = 360.0 / m_notches;
for (int i = 0; i < m_notches; ++i) {
painter.save();
painter.translate(rect().center());
painter.rotate(i * step);
painter.drawLine(QPointF(0, -30), QPointF(0, -40));
painter.restore();
}
}
void mousePressEvent(QMouseEvent *event) override
{
if (event->button() == Qt::LeftButton) {
QPoint center = rect().center();
qreal angle = atan2(event->y() - center.y(), event->x() - center.x()) * 180 / M_PI + 90;
if (angle < 0)
angle += 360;
qreal step = 360.0 / m_notches;
if (angle < step / 2 || angle >= 360 - step / 2)
m_value = 0;
else if (angle < 180 - step / 2)
m_value = 50;
else
m_value = 100;
update();
}
QWidget::mousePressEvent(event);
}
private:
int m_value;
int m_notches;
};
```
在这个示例中,我们继承自QWidget,并重写了paintEvent()和mousePressEvent()方法。在paintEvent()方法中,我们使用QPainter绘制了背景圆形、指针和挡位。在mousePressEvent()方法中,我们通过计算鼠标点击的角度来设置不同的挡位,并更新控件的值。您可以根据需要更改设置挡位的逻辑,并根据您的具体需求进行自定义。
阅读全文