横棒グラフの作成

注: これは、ウィジェット・ギャラリーによるチャートの例の一部です。

QHorizontalBarChart は、セット内のデータを別々のバーとして表示し、それらはカテゴリーでグループ化されます。QHorizontalBarChart は QBarChart と同様に機能しますが、バーがチャート上に水平に描画されます。

バー・セットは、すべての棒グラフで同じように使用されます。さまざまな棒グラフの違いを説明するために、すべての例で同じデータを使用します。棒グラフが可視化するデータは、QBarSet インスタンスによって定義されます。ここでは、セットを作成し、そこにデータを追加する。ここでは<<演算子を使ってデータを追加している。あるいは、append メソッドを使うこともできる。

auto set0 = new QBarSet("Jane");
auto set1 = new QBarSet("John");
auto set2 = new QBarSet("Axel");
auto set3 = new QBarSet("Mary");
auto set4 = new QBarSet("Samantha");

*set0 << 1 << 2 << 3 << 4 << 5 << 6;
*set1 << 5 << 0 << 0 << 4 << 0 << 7;
*set2 << 3 << 5 << 8 << 13 << 8 << 5;
*set3 << 5 << 6 << 7 << 3 << 4 << 5;
*set4 << 9 << 7 << 5 << 3 << 1 << 2;

シリーズを作成し、そこにバーセットを追加する。系列はバーセットの所有権を持つ。系列は、データをセットからカテゴリにグループ化します。各セットの最初の値は最初のカテゴリーにまとめられ、2番目の値は2番目のカテゴリーにまとめられます。

auto series = new QHorizontalBarSeries;
series->append(set0);
series->append(set1);
series->append(set2);
series->append(set3);
series->append(set4);

ここでは、チャート・オブジェクトを作成し、そこに系列を追加します。setTitleでチャートのタイトルを設定し、setAnimationOptions(QChart::SeriesAnimations)を呼び出して系列のアニメーションをオンにします。

auto chart = new QChart;
chart->addSeries(series);
chart->setTitle("Simple Horizontal Bar Chart");
chart->setAnimationOptions(QChart::SeriesAnimations);

軸上にカテゴリを表示するには、QBarCategoryAxis 。ここでは、カテゴリのリストでカテゴリ軸を作成し、それを左側に整列してy軸として機能するように設定し、それを系列にアタッチします。チャートが軸の所有権を持ちます。x軸には、底に整列した値軸を使用します。

QStringList categories {"Jan", "Feb", "Mar", "Apr", "May", "Jun"};
auto axisY = new QBarCategoryAxis;
axisY->append(categories);
chart->addAxis(axisY, Qt::AlignLeft);
series->attachAxis(axisY);
auto axisX = new QValueAxis;
chart->addAxis(axisX, Qt::AlignBottom);
series->attachAxis(axisX);
axisX->applyNiceNumbers();

凡例も表示したい。そのために、チャートから凡例ポインタを取得して、それを可視に設定します。また、アライメントをQt::AlignBottom に設定して、凡例をチャートの一番下に配置します。

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

最後に、チャートをビューに追加します。また、chartViewのアンチエイリアスをオンにします。

createDefaultChartView(chart);

これでチャートを表示する準備が整いました。

© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.