温馨提示×

qt怎么绘制坐标轴和刻度

qt
小亿
121
2024-05-15 19:24:17
栏目: 编程语言

在Qt中绘制坐标轴和刻度可以通过继承QWidget类并重写其paintEvent方法来实现。以下是一个简单的示例代码:

#include <QtWidgets>

class PlotWidget : public QWidget
{
public:
    PlotWidget(QWidget *parent = nullptr) : QWidget(parent) {}

protected:
    void paintEvent(QPaintEvent *event) override
    {
        Q_UNUSED(event);

        QPainter painter(this);

        painter.setRenderHint(QPainter::Antialiasing, true);

        // 绘制坐标轴
        painter.drawLine(50, height() - 50, 50, 50); // 纵轴
        painter.drawLine(50, height() - 50, width() - 50, height() - 50); // 横轴

        // 绘制刻度
        int numTicks = 10;
        for (int i = 0; i <= numTicks; ++i)
        {
            int x = 50 + i * (width() - 100) / numTicks;
            painter.drawLine(x, height() - 50, x, height() - 45); // 底部刻度
            painter.drawLine(50, height() - 50 - i * (height() - 100) / numTicks, 45, height() - 50 - i * (height() - 100) / numTicks); // 左侧刻度
        }
    }
};

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    PlotWidget plot;
    plot.resize(400, 300);
    plot.show();

    return app.exec();
}

在上面的示例中,绘制了一个简单的坐标轴和刻度,纵轴和横轴分别位于左侧和底部,刻度的数量为10个。可以根据具体需求对绘制坐标轴和刻度的样式进行调整。

0