c++user-interfaceqt5qt-creatorqtcharts

How to draw bars between ticks in a QtCharts Widget?


I'm attempting to create a bar chart using QtCharts. I want to have an horizontal axis of numeric values and my bars to be displayed in between the ticks. However, it seems that, differently from the case of a QBarCategoryAxis in which the labels will be centralized at the bars (each bar representing a category), the QValueAxis behavior is to centralize the bars in the ticks.

enter image description here

    QBarSet *set0 = new QBarSet("Dummy");
    int dummy_value = 5;
    *set0 << dummy_value
          << dummy_value + 2
          << dummy_value + 4;

    QStackedBarSeries *series = new QStackedBarSeries();
    series->append(set0);
    series->setBarWidth(1.0);

    QChart *chart = new QChart();
    chart->addSeries(series);
    chart->setTitle("Dummy");

    QValueAxis* y_axis = new QValueAxis();
    chart->addAxis(y_axis, Qt::AlignLeft);
    y_axis->setRange(0, 10);
    y_axis->setTickCount(6);
    y_axis->setLabelFormat("%i");
    y_axis->setVisible(true);
    series->attachAxis(y_axis);

    QValueAxis* x_axis = new QValueAxis();
    chart->addAxis(x_axis, Qt::AlignBottom);
    x_axis->setRange(0, set0->count());
    x_axis->setTickCount(set0->count() + 1);
    x_axis->setLabelFormat("%d");
    x_axis->setVisible(true);
    series->attachAxis(x_axis);

    chart->legend()->setVisible(true);
    chart->legend()->setAlignment(Qt::AlignBottom);

Does anyone know a good solution to have the bars displayed between the ticks while also having the labels displayed on the ticks rather than centralized on the bars?


Solution

  • I got the behavior I wanted by suppressing the line

    series->attachAxis(x_axis);