qt 自定义旋钮并计算旋转角度示例
时间: 2023-07-13 07:10:20 浏览: 116
Qt自定义旋转刷新按钮
以下是一个简单的自定义旋钮控件示例,它可以根据旋钮的位置计算旋转角度:
```cpp
#include <QPainter>
#include <QMouseEvent>
#include <QtMath>
#include <QWidget>
class Knob : public QWidget {
Q_OBJECT
public:
explicit Knob(QWidget *parent = nullptr) : QWidget(parent) {
m_minimumValue = 0;
m_maximumValue = 100;
m_value = 0;
m_mousePressed = false;
}
void setRange(int minimumValue, int maximumValue) {
m_minimumValue = minimumValue;
m_maximumValue = maximumValue;
}
void setValue(int value) {
m_value = qBound(m_minimumValue, value, m_maximumValue);
update();
}
int value() const {
return m_value;
}
signals:
void valueChanged(int value);
protected:
void paintEvent(QPaintEvent *event) override {
Q_UNUSED(event);
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing, true);
painter.save();
painter.translate(width() / 2, height() / 2);
// 绘制旋钮背景
painter.setPen(Qt::NoPen);
painter.setBrush(QColor(127, 127, 127));
painter.drawEllipse(QRectF(-50, -50, 100, 100));
// 绘制旋钮指针
painter.rotate((m_value - m_minimumValue) * 300.0 / (m_maximumValue - m_minimumValue) - 150.0);
painter.setBrush(QColor(255, 255, 255));
painter.drawEllipse(QRectF(-10, -50, 20, 100));
painter.restore();
}
void mousePressEvent(QMouseEvent *event) override {
if (event->button() == Qt::LeftButton) {
m_mousePressed = true;
updateValue(event->pos());
}
}
void mouseMoveEvent(QMouseEvent *event) override {
if (m_mousePressed) {
updateValue(event->pos());
}
}
void mouseReleaseEvent(QMouseEvent *event) override {
if (event->button() == Qt::LeftButton) {
m_mousePressed = false;
}
}
private:
void updateValue(const QPoint &pos) {
qreal dx = pos.x() - width() / 2;
qreal dy = pos.y() - height() / 2;
qreal angle = qAtan2(dy, dx);
int value = qBound(m_minimumValue, qRound((angle + M_PI) * (m_maximumValue - m_minimumValue) / (2 * M_PI)), m_maximumValue);
if (m_value != value) {
m_value = value;
emit valueChanged(m_value);
update();
}
}
int m_minimumValue;
int m_maximumValue;
int m_value;
bool m_mousePressed;
};
```
使用示例:
```cpp
// 创建自定义旋钮控件
Knob *knob = new Knob(this);
knob->setRange(0, 100);
// 监听旋钮值变化信号
connect(knob, &Knob::valueChanged, [=](int value) {
qDebug() << "Value changed:" << value;
});
// 设置旋钮初始值
knob->setValue(50);
```
在上面的代码中,我们重写了 `paintEvent` 方法来绘制旋钮的背景和指针。在 `mousePressEvent`、`mouseMoveEvent` 和 `mouseReleaseEvent` 方法中,我们处理鼠标事件来更新旋钮的值。在 `updateValue` 方法中,我们通过计算鼠标位置与旋钮中心的角度来计算旋钮的值。最后我们使用 `emit` 语句发射 `valueChanged` 信号来通知旋钮值的变化。
阅读全文