Search code examples
qtqcustomplot

Custom formatting numbers in axes of QCustomPlot


I would like to set the formatting of numbers in axes of QCustomPlot. I know how to deal with decimal precision, but have no idea, how to use spaces instead of commas in case of large numbers.

I would like numbers to look like this:

1.045   (decimals separated with a dot)
1 000  (thousands separated with space, currently I get 1,000)

there is a method QCPAxis::setNumberFormat, which seems to not be what I am looking for.


Solution

  • You need to subclass QCPAxisTicker and reimplement getTickLabel method

    I couldn't find locale that would do spaces as group separator and dot as decimal point so i instead used QString replace function to make "custom separators".

    Quick and dirty example:

    QString getTickLabel (double tick, const QLocale &locale, QChar formatChar, int precision) {
        QLocale l;
        QString number = l.toString(tick, 'g', 15);
        number.replace(l.decimalPoint(), ".");
        number.replace(l.groupSeparator(), " ");
    
        return number;
    }
    

    input:

    1000000.1411
    

    output:

    "1 000 000.1411"