更改 QCategoryAxis 中每个标签的文本颜色

Changing text color for each label in QCategoryAxis

有没有办法为 QCategoryAxis 中的每个标签分配颜色?

我知道我可以有一个图例,但我更喜欢在轴上设置颜色以匹配我拥有的线条的颜色。我想更改标记(类别文本)本身的颜色,而不是刻度线。请注意,我想为每个轴标签设置不同的颜色。

尝试使用 axisY.setLabelsBrush(QBrush(Qt::red)); 但是这会为所有标签设置相同的颜色。

使用 Qt 5.10

QCategoryAxis的标签是QGraphicsTextItem所以他们支持HTML,所以你可以通过那个方法传递颜色:

#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();
}