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
AD

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:50points,
  • Rating points-4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:20points,
  • Rating points-10
Last comments
ИМ
Игорь МаксимовNov. 22, 2024, 8:51 a.m.
Django - Tutorial 017. Customize the login page to Django Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
Evgenii Legotckoi
Evgenii LegotckoiOct. 31, 2024, 11:37 a.m.
Django - Lesson 064. How to write a Python Markdown extension Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
A
ALO1ZEOct. 19, 2024, 5:19 a.m.
Fb3 file reader on Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
ИМ
Игорь МаксимовOct. 5, 2024, 4:51 a.m.
Django - Lesson 064. How to write a Python Markdown extension Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
d
dblas5July 5, 2024, 8:02 a.m.
QML - Lesson 016. SQLite database and the working with it in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
Now discuss on the forum
Evgenii Legotckoi
Evgenii LegotckoiJune 24, 2024, 12:11 p.m.
добавить qlineseries в функции Я тут. Работы оень много. Отправил его в бан.
t
tonypeachey1Nov. 15, 2024, 3:04 a.m.
google domain [url=https://google.com/]domain[/url] domain [http://www.example.com link title]
NSProject
NSProjectJune 4, 2022, 12:49 a.m.
Всё ещё разбираюсь с кешем. В следствии прочтения данной статьи. Я принял для себя решение сделать кеширование свойств менеджера модели LikeDislike. И так как установка evileg_core для меня не была возможна, ибо он писался…
9
9AnonimOct. 25, 2024, 6:10 a.m.
Машина тьюринга // Начальное состояние 0 0, ,<,1 // Переход в состояние 1 при пустом символе 0,0,>,0 // Остаемся в состоянии 0, двигаясь вправо при встрече 0 0,1,>…

Follow us in social networks