StackedBarChart Drilldown Example

In the drilldown example we create a stacked bar chart, which shows the harvest of various chili peppers during season. In season view the harvest is grouped by month. To drill down to weekly view, right-click the selected month. On weekly view, the harvest of the month clicked is shown by week.

The season view looks like this:

Image non disponible

Clicking on a month shows that month's harvest:

Image non disponible

Running the Example

To run the example from Qt Creator, open the Welcome mode and select the example from Examples. For more information, visit Building and Running an Example.

Implementing Drilldown

First we define a drilldown series class, which adds categories to the stacked bar series and mapping for categories to other drilldown series. The purpose of the drilldown series is to contain knowledge of the drilldown structure. The mapDrilldownSeries function maps the category to a given series. We can request the mapping for a category with the drilldownSeries(int category) function.

 
Sélectionnez
class DrilldownBarSeries : public QStackedBarSeries
{
    Q_OBJECT
public:
    DrilldownBarSeries(QStringList categories, int maxValue, QObject *parent = 0);

    void mapDrilldownSeries(int index, DrilldownBarSeries *drilldownSeries);

    DrilldownBarSeries *drilldownSeries(int index);

    QStringList categories();

    int maxValue();

private:
    QMap<int, DrilldownBarSeries *> m_DrilldownSeries;
    QStringList m_categories;
    int m_maxValue;
};

Next we define our own drilldown chart, which implements the handler for the mouse click. All QBarSeries derived classes send out the clicked(QBarSet*, int) signal when a series is clicked with the mouse. The parameter QBarSet contains the pointer to the clicked bar set and parameter int contains the index of the clicked category.

 
Sélectionnez
class DrilldownChart : public QChart
{
    Q_OBJECT
public:
    explicit DrilldownChart(QGraphicsItem *parent = 0, Qt::WindowFlags wFlags = 0);

    void changeSeries(DrilldownBarSeries *series);

public Q_SLOTS:
    void handleClicked(int index, QBarSet *barset);

private:
    DrilldownBarSeries *m_currentSeries;
    QBarCategoryAxis *m_axisX;
    QValueAxis *m_axisY;
};

Now we have our drilldown classes and we can start using them. First create the chart.

 
Sélectionnez
    DrilldownChart *drilldownChart =  new DrilldownChart();
    drilldownChart->setAnimationOptions(QChart::SeriesAnimations);

We define the categories from which the drilldown series will be constructed.

 
Sélectionnez
    // Define categories
    const QStringList months = {
        "May", "Jun", "Jul", "Aug", "Sep"
    };
    const QStringList weeks = {
        "week 1", "week 2", "week 3", "week 4"
    };
    const QStringList plants = {
        "Habanero", "Lemon Drop", "Starfish", "Aji Amarillo"
    };