QT4.5可以绘制图表发方法函数
时间: 2023-06-15 18:05:54 浏览: 44
在Qt 4.5中,你可以使用QCustomPlot库来绘制图表。QCustomPlot是一个基于Qt的开源C++图表库,可以绘制多种类型的图表,包括线图、散点图、柱状图等等。
以下是使用QCustomPlot绘制简单曲线图的示例代码:
1. 首先,你需要将QCustomPlot库添加到你的Qt项目中,可以通过在.pro文件中添加以下代码来实现:
```
QT += widgets
INCLUDEPATH += /path/to/qcustomplot
LIBS += -L/path/to/qcustomplot -lqcustomplot
```
2. 在你的Qt代码中,包含QCustomPlot头文件:
```
#include "qcustomplot.h"
```
3. 在你的Qt界面中添加一个QCustomPlot小部件。
4. 在你的Qt代码中,创建一个QCustomPlot对象,并设置图表的属性,例如:
```
QCustomPlot *customPlot = new QCustomPlot(this);
customPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom);
customPlot->xAxis->setLabel("x");
customPlot->yAxis->setLabel("y");
```
5. 创建一个QVector对象存储x和y坐标值,例如:
```
QVector<double> x(101), y(101);
for (int i=0; i<101; ++i)
{
x[i] = i/5.0 - 10;
y[i] = qSin(x[i])/x[i];
}
```
6. 使用addGraph()函数将曲线添加到图表中,并设置曲线的样式,例如:
```
customPlot->addGraph();
customPlot->graph(0)->setData(x, y);
customPlot->graph(0)->setPen(QPen(Qt::blue));
customPlot->graph(0)->setLineStyle(QCPGraph::lsLine);
```
7. 调用replot()函数重新绘制图表:
```
customPlot->replot();
```
完整示例代码:
```
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "qcustomplot.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
// create custom plot and set its properties
QCustomPlot *customPlot = new QCustomPlot(this);
customPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom);
customPlot->xAxis->setLabel("x");
customPlot->yAxis->setLabel("y");
// create data
QVector<double> x(101), y(101);
for (int i=0; i<101; ++i)
{
x[i] = i/5.0 - 10;
y[i] = qSin(x[i])/x[i];
}
// add graph and set its properties
customPlot->addGraph();
customPlot->graph(0)->setData(x, y);
customPlot->graph(0)->setPen(QPen(Qt::blue));
customPlot->graph(0)->setLineStyle(QCPGraph::lsLine);
// replot the graph
customPlot->replot();
// add custom plot widget to main window
ui->verticalLayout->addWidget(customPlot);
}
MainWindow::~MainWindow()
{
delete ui;
}
```
运行以上代码,你将看到一个简单的曲线图。你可以使用QCustomPlot库的其他函数来绘制不同类型的图表,并设置各种属性。