qt怎么绘制坐标轴和刻度

qt
1912
2024/5/12 19:24:17
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在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个。可以根据具体需求对绘制坐标轴和刻度的样式进行调整。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: QT怎么连接Mysql数据库并添加数据