Huier_YFB 2024-03-13 15:44 采纳率: 0%
浏览 99

QChart如何在图例上方加标签?

我想在一个柱状图的图例上方加个标签,如图所示:

img


使用环境哪个标签怎么加?

  • 写回答

3条回答 默认 最新

  • 关注

    Huier_YFB 下午好🌅🌅🌅
    本答案参考ChatGPT-3.5

    要在QChart的图例上方加标签,可以通过以下步骤实现:

    1. 使用QChart的setTitle()函数设置图例的标题。
    chart->legend()->setTitleText("标签");
    
    1. 创建一个QLabel控件,并将其设置为图例的子控件。
    QLabel *label = new QLabel("标签", chart);
    
    1. 调整标签的位置,使其位于图例上方。
    label->setGeometry(chart->legend()->geometry().x(), chart->legend()->geometry().y() - label->height() - 5, chart->legend()->width(), label->height());
    

    完整示例代码如下:

    QChart *chart = new QChart();
    // 创建柱状图,并将其添加到图表中
    QBarSeries *series = new QBarSeries();
    series->append(new QBarSet("出"));
    series->append(new QBarSet("安"));
    series->append(new QBarSet("电量监测"));
    series->setLabelsVisible(true);
    
    chart->addSeries(series);
    
    QValueAxis *axisY = new QValueAxis;
    chart->addAxis(axisY, Qt::AlignLeft);
    series->attachAxis(axisY);
    
    QBarCategoryAxis *axisX = new QBarCategoryAxis;
    chart->addAxis(axisX, Qt::AlignBottom);
    series->attachAxis(axisX);
    
    // 设置图例
    chart->legend()->setVisible(true);
    chart->legend()->setAlignment(Qt::AlignBottom);
    
    // 设置图例标题
    chart->legend()->setTitleText("标签");
    
    // 添加标签
    QLabel *label = new QLabel("标签", chart);
    label->setGeometry(chart->legend()->geometry().x(), chart->legend()->geometry().y() - label->height() - 5, chart->legend()->width(), label->height());
    

    注意:上述示例中的代码是基于Qt的QChart模块,如果你使用的是其他绘图库或工具,可能需要相应的调整。

    评论

报告相同问题?

问题事件

  • 创建了问题 3月13日