Search code examples
c++qtqt5qtcharts

Changing text color for each label in QCategoryAxis


Is there a way to assign a color for each label in a QCategoryAxis?

I know I can have a legend, but I prefer setting the colors on the axis to match the colors of the lines I have. I want to change the color of the markers (text of the categories) themselves, not the ticks. Notice that I want to set a different color for each axis label.

Tried using axisY.setLabelsBrush(QBrush(Qt::red)); But this sets the same color for all the labels.

Using Qt 5.10


Solution

  • the labels of QCategoryAxis are QGraphicsTextItem so they support HTML, so you could pass the color through that method:

    #include <QApplication>
    #include <QMainWindow>
    #include <QtCharts>
    
    QT_CHARTS_USE_NAMESPACE
    
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
    
        QLineSeries *series = new QLineSeries();
        *series << QPointF(0, 6) << QPointF(9, 4) << QPointF(15, 20) << QPointF(25, 12) << QPointF(29, 26);
        QChart *chart = new QChart();
        chart->legend()->hide();
        chart->addSeries(series);
    
        QCategoryAxis *axisX = new QCategoryAxis();
        QCategoryAxis *axisY = new QCategoryAxis();
    
        // Customize axis label font
        QFont labelsFont;
        labelsFont.setPixelSize(12);
        axisX->setLabelsFont(labelsFont);
        axisY->setLabelsFont(labelsFont);
    
        // Customize axis colors
        QPen axisPen(QRgb(0xd18952));
        axisPen.setWidth(2);
        axisX->setLinePen(axisPen);
        axisY->setLinePen(axisPen);
    
        axisX->append("<span style=\"color: #339966;\">low</span>", 10);
        axisX->append("<span style=\"color: #330066;\">optimal</span>", 20);
        axisX->append("<span style=\"color: #55ff66;\">high</span>", 30);
        axisX->setRange(0, 30);
    
        axisY->append("<font color=\"red\">slow</font>", 10);
        axisY->append("<font color=\"green\">med</font>", 20);
        axisY->append("<span style=\"color: #ffff00;\">fast</span>", 30);
        axisY->setRange(0, 30);
    
        chart->setAxisX(axisX, series);
        chart->setAxisY(axisY, series);
        QChartView *chartView = new QChartView(chart);
        chartView->setRenderHint(QPainter::Antialiasing);
    
    
        QMainWindow window;
        window.setCentralWidget(chartView);
        window.resize(400, 300);
        window.show();
    
        return a.exec();
    }
    

    enter image description here