QChart画折线图
一、效果(带点标签的折线图)
二、代码
#include <QtWidgets/QMainWindow>
#include <QApplication>
#include "math.h"
#include <QtCharts>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
// 折线
QLineSeries *series = new QLineSeries();
// 画心
double xx,yy;
for(double t=-3; t<=3; t=t+0.1)
{
xx = 16*pow(sin(t),3);
yy = 13*cos(t)-5*cos(t*2)-2*cos(t*3)-cos(t*4);
//画点
series->append(xx, yy);
}
// 设置点标签
series->setPointLabelsFormat("@yPoint");
series->setPointLabelsClipping(false);
series->setPointLabelsVisible(true);
QFont *font = new QFont();
font->setPointSize(6);
series->setPointLabelsFont(*font);
QChart *chart = new QChart();
chart->legend()->hide();
chart->addSeries(series);
chart->setTitle("哈哈");
QChartView *chartView = new QChartView(chart);
chartView->setRenderHint(QPainter::Antialiasing);
// 创建主窗体 并显示
QMainWindow window;
window.setCentralWidget(chartView);
window.resize(400, 300);
window.show();
return a.exec();
}
三、关于点标签
官方的文档1里很简单的一句话:
3.1 源码
/*!
\property QXYSeries::pointLabelsFormat
\brief The format used for showing labels with data points.
QXYSeries supports the following format tags:
@xPoint The x-coordinate of the data point.
@yPoint The y-coordinate of the data point.
\code
series->setPointLabelsFormat("(@xPoint, @yPoint)");
*/
void QXYSeries::setPointLabelsFormat(const QString &format)
{
Q_D(QXYSeries);
if (d->m_pointLabelsFormat != format) {
d->m_pointLabelsFormat = format;
emit pointLabelsFormatChanged(format);
}
}
参数很少,只能显示点的坐标
想要继续深入可研究pointLabelsFormatChanged函数
3.2 参考博文
QXYSeries类的API及其使用2:QtCharts之QXYSeries
QLineSeries类详解3:QLineSeries类详解
很有创意的想法,将QLabel当做图的label4:QPieSeries中心添加文字
关于命名空间的坑5:在使用QChart的时候要加上命名空间