qt怎么繪制坐標(biāo)軸和刻度

qt
小億
297
2024-05-15 19:24:17

在Qt中繪制坐標(biāo)軸和刻度可以通過繼承QWidget類并重寫其paintEvent方法來實(shí)現(xiàn)。以下是一個(gè)簡(jiǎn)單的示例代碼:

#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);

        // 繪制坐標(biāo)軸
        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); // 左側(cè)刻度
        }
    }
};

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

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

    return app.exec();
}

在上面的示例中,繪制了一個(gè)簡(jiǎn)單的坐標(biāo)軸和刻度,縱軸和橫軸分別位于左側(cè)和底部,刻度的數(shù)量為10個(gè)??梢愿鶕?jù)具體需求對(duì)繪制坐標(biāo)軸和刻度的樣式進(jìn)行調(diào)整。

0