mafulechka
mafulechkaJune 24, 2019, 4:48 a.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.

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
e
  • ehot
  • March 31, 2024, 9:29 p.m.

C++ - Тест 003. Условия и циклы

  • Result:78points,
  • Rating points2
B

C++ - Test 002. Constants

  • Result:16points,
  • Rating points-10
B

C++ - Test 001. The first program and data types

  • Result:46points,
  • Rating points-6
Last comments
k
kmssrFeb. 9, 2024, 2:43 a.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 6:30 p.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 4:38 p.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 19, 2023, 5:01 a.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
a
a_vlasovApril 14, 2024, 1:41 p.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
Павел Дорофеев
Павел ДорофеевApril 14, 2024, 9:35 a.m.
QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
f
fastrexApril 4, 2024, 11:47 a.m.
Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…
AC
Alexandru CodreanuJan. 19, 2024, 7:57 p.m.
QML Обнулить значения SpinBox Доброго времени суток, не могу разобраться с обнулением значение SpinBox находящего в делегате. import QtQuickimport QtQuick.ControlsWindow { width: 640 height: 480 visible: tr…

Follow us in social networks