#include <QApplication>
#include <QWidget>
#include <QPainter>
#include <QWheelEvent>
#include <cmath>
#define M_PI 3.14159265358979323846
class RulerWidget : public QWidget
{
public:
RulerWidget(QWidget *parent = nullptr) : QWidget(parent), scaleFactor(1.0) { }
protected:
void paintEvent(QPaintEvent *event) override
{
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
painter.scale(scaleFactor, scaleFactor);
int width = this->width() / scaleFactor;
int height = this->height() / scaleFactor;
// 绘制坐标轴
drawArrow(painter, 50, height - 50, 50, 50); // Y轴
drawArrow(painter, 50, height - 50, width - 50, height - 50); // X轴
// 绘制X轴刻度
int numXTicks = 10;
int xSpacing = (width - 100) / numXTicks;
for (int i = 0; i <= numXTicks; ++i) {
int x = 50 + i * xSpacing;
painter.drawLine(x, height - 50, x, height - 40);
painter.drawText(x - 5, height - 30, QString::number(i)); // 显示X轴刻度值
}
// 绘制Y轴刻度
int numYTicks = 10;
int ySpacing = (height - 100) / numYTicks;
for (int i = 0; i <= numYTicks; ++i) {
int y = height - 50 - i * ySpacing;
painter.drawLine(40, y, 50, y);
painter.drawText(20, y + 5, QString::number(i)); // 显示Y轴刻度值
}
// 添加X轴标记Text
painter.drawText(width - 30, height - 20, "X Axis");
// 添加Y轴标记Text
painter.drawText(10, 20, "Y Axis");
}
void drawArrow(QPainter &painter, int x1, int y1, int x2, int y2)
{
painter.drawLine(x1, y1, x2, y2);
double angle = atan2(y2 - y1, x2 - x1);
double arrowSize = 10;
painter.drawLine(x2, y2, x2 - arrowSize * cos(angle - M_PI / 6), y2 - arrowSize * sin(angle - M_PI / 6));
painter.drawLine(x2, y2, x2 - arrowSize * cos(angle + M_PI / 6), y2 - arrowSize * sin(angle + M_PI / 6));
}
void wheelEvent(QWheelEvent *event) override
{
int numDegrees = event->angleDelta().y() / 8;
double numSteps = numDegrees / 15.0;
scaleFactor += numSteps;
if (scaleFactor < 0.1) {
scaleFactor = 0.1;
}
update();
}
private:
double scaleFactor;
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
RulerWidget widget;
widget.resize(400, 300);
widget.show();
return app.exec();
}
12-21
1149
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
05-26
12-18
2709
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
07-24
546
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
07-19
1204
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)