mafulechka
June 24, 2019, 2:48 p.m.

Qt Support - Aligning Chart Views to Each Other

One thing that comes up in support from time to time is that when you have multiple chart types, it's good to align them to each other so that the actual chart size is the same for both charts. If you have the same axle sizes this is easy to achieve as they will take up the same width and align accordingly. However, if it isn't, which is often the case, then we can use margins to force it to take on the desired dimensions.


So let's imagine our graph currently looks like this:

If you are using C++ for your chart code, this can be achieved with a single slot that can be connected to the QChart::plotAreaChanged() signal.
First we need to prevent recursion since we'll be changing fields, but since we want the internals to keep doing their thing, we won't block the signals. To do this, we'll have a static boolean that we'll set to true to indicate that we're in the middle of our calculations:

void updatePlotArea(const QRectF &area)
    {
        static bool fixing = false;
        if (fixing)
            return;
        fixing = true;

The next thing we need to do is determine which chart is best to use to equalize the others. This means picking the one with the largest left value for the plot area (i.e. the one with the widest axis). We are currently using "modified" as a starting point, and if there are any, we are changing the margins for them, as this will provide the largest size available for the plot area at any given point for the largest axis.

QChart *bestChart = (QChart *)sender();
         QRectF bestRect = area;
         foreach(QChart *chart, charts) {
            if (chart->plotArea().left() > bestRect.left()) {
                bestChart = chart;
                bestRect = chart->plotArea();
                chart->setMargins(QMargins(20, 0, 20, 0));
             }
         }

Then, with the exception of the one that happens to be the "best" (bestChart), we adjust the margins to make sure they match the "best" and align correctly, setting the margins to be the existing margin plus the difference between the area of the "best" chart and the current one. Finally, we send any published events to be immediately updated for us.

foreach(QChart *chart, charts) {
        if (bestChart != chart) {
            const int left = chart->margins().left() +
                (bestRect.left() - chart->plotArea().left());
            const int right = chart->margins().right() +
                (chart->plotArea().right() - bestRect.right());
            chart->setMargins(QMargins(left, 0, right, 0));
        }
    }
    QApplication::sendPostedEvents();
    fixing = false;

This will give us two aligned plots that look like this:

As far as QML is concerned, we can do something similar through a function that is called with onPlotAreaChanged .

property bool fixing: false
    property var chartViews: [chartview, chartview_b]
    function updatePlotArea(chart, area) {
        if (fixing)
            return
        fixing = true
        var tmpChart
        var bestRect = chart.plotArea
        var bestChart = chart
        for (var i = 0; i  Math.ceil(bestRect.left) ||
           (Math.ceil(tmpChart.plotArea.left) === 
            Math.ceil(bestRect.left) &&
            Math.floor(tmpChart.plotArea.right) < 
            Math.floor(bestRect.right))) {
                bestChart = tmpChart;
                bestRect = tmpChart.plotArea;
            }
        }
        bestRect.left = Math.ceil(bestRect.left)
        bestRect.right = Math.floor(bestRect.right)
        for (i = 0; i < chartViews.length; i++) {
            tmpChart = chartViews[i]
            if (tmpChart !== bestChart) {
                var newLeft = 20 + bestRect.left -
                      Math.floor(tmpChart.plotArea.left);
                var newRight = 20 +
                      Math.ceil(tmpChart.plotArea.right) -
                      bestRect.right;
                tmpChart.margins.left = newLeft
                tmpChart.margins.right = newRight
            }
        }
        fixing = false;
    }

The only difference is that we account for the fact that the plot area uses real values and the fields are still integer based, so we make some extra credentials as a result.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • AK
    April 24, 2025, 12:04 p.m.
    UPD: Переписал логику воспроизведения через стороннюю библиотеку BASS. Там выбрать можно
  • Evgenii Legotckoi
    April 16, 2025, 5:08 p.m.
    Благодарю за отзыв. И вам желаю всяческих успехов!
  • IscanderChe
    April 12, 2025, 5:12 p.m.
    Добрый день. Спасибо Вам за этот проект и отдельно за ответы на форуме, которые мне очень помогли в некоммерческих пет-проектах. Профессиональным программистом я так и не стал, но узнал мно…
  • AK
    April 1, 2025, 11:41 a.m.
    Добрый день. В данный момент работаю над проектом, где необходимо выводить звук из программы в определенное аудиоустройство (колонки, наушники, виртуальный кабель и т.д). Пишу на Qt5.12.12 поско…
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…