完善代码中的红线指针随鼠标移动而移动,黄线指针在鼠标点击时发生移动的代码
时间: 2024-03-11 22:48:45 浏览: 144
随着鼠标移动出现不同内容效果代码
以下是完善后的代码,可以实现红线指针随鼠标移动而移动,黄线指针在鼠标点击时发生移动,并且可以计算出两个指针之间的夹角,并在UI界面上显示角度。
```cpp
#include <QtWidgets>
class CircleWidget : public QWidget
{
public:
CircleWidget(QWidget *parent = nullptr)
: QWidget(parent)
{
m_angleRed = 0;
m_angleYellow = 0;
}
void setAngleRed(qreal angle)
{
m_angleRed = angle;
update();
}
void setAngleYellow(qreal angle)
{
m_angleYellow = angle;
update();
}
qreal angle() const
{
return m_angleRed - m_angleYellow;
}
protected:
void paintEvent(QPaintEvent *event) override
{
Q_UNUSED(event);
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
// 绘制圆形图
painter.setPen(Qt::black);
painter.drawEllipse(rect().adjusted(10, 10, -10, -10));
// 绘制刻度线
painter.save();
painter.translate(rect().center());
painter.rotate(-45);
for (int i = 0; i < 12; ++i) {
painter.drawLine(0, -100, 0, -90);
painter.rotate(30);
}
painter.restore();
// 绘制指针
painter.save();
painter.translate(rect().center());
// 红色指针
painter.rotate(m_angleRed);
painter.setPen(Qt::red);
painter.drawLine(0, 0, 0, -60);
// 黄色指针
painter.rotate(m_angleYellow - m_angleRed);
painter.setPen(Qt::yellow);
painter.drawLine(0, 0, 0, -80);
painter.restore();
}
private:
qreal m_angleRed;
qreal m_angleYellow;
};
class MainWindow : public QMainWindow
{
public:
MainWindow(QWidget *parent = nullptr)
: QMainWindow(parent)
{
m_circleWidget = new CircleWidget(this);
setCentralWidget(m_circleWidget);
connect(m_circleWidget, &CircleWidget::mousePressEvent, this, &MainWindow::onMousePress);
connect(m_circleWidget, &CircleWidget::mouseMoveEvent, this, &MainWindow::onMouseMove);
m_label = new QLabel(this);
statusBar()->addWidget(m_label);
}
private:
void onMousePress(QMouseEvent *event)
{
m_lastPoint = event->pos();
QPoint center = m_circleWidget->rect().center();
qreal dx = m_lastPoint.x() - center.x();
qreal dy = m_lastPoint.y() - center.y();
m_angleYellow = qAtan2(dy, dx) * 180 / M_PI;
m_circleWidget->setAngleYellow(m_angleYellow);
}
void onMouseMove(QMouseEvent *event)
{
QPoint currentPoint = event->pos();
QPoint center = m_circleWidget->rect().center();
qreal dx1 = m_lastPoint.x() - center.x();
qreal dy1 = m_lastPoint.y() - center.y();
qreal dx2 = currentPoint.x() - center.x();
qreal dy2 = currentPoint.y() - center.y();
qreal angle1 = qAtan2(dy1, dx1) * 180 / M_PI;
qreal angle2 = qAtan2(dy2, dx2) * 180 / M_PI;
qreal deltaAngle = angle2 - angle1;
if (deltaAngle < -180) {
deltaAngle += 360;
} else if (deltaAngle > 180) {
deltaAngle -= 360;
}
m_angleRed += deltaAngle;
m_circleWidget->setAngleRed(m_angleRed);
m_lastPoint = currentPoint;
m_label->setText(QString("Angle: %1 degrees").arg(m_circleWidget->angle()));
}
QPoint m_lastPoint;
qreal m_angleYellow;
qreal m_angleRed;
CircleWidget *m_circleWidget;
QLabel *m_label;
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
```
注意:这个代码只是一个示例,可能需要根据实际需求进行修改和完善。
阅读全文