更改QCategoryAxis

时间:2018-05-03 13:18:44

标签: c++ qt qt5 qtchart

有没有办法为QCategoryAxis中的每个标签指定颜色?

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

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

使用Qt 5.10

1 个答案:

答案 0 :(得分:2)

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

enter image description here