我需要使用qt中的QChartView在QWidget上画一个直方图,请写出代码
时间: 2024-05-04 17:16:15 浏览: 215
QWT直方图源代码
好的,以下是一个在QWidget上画直方图的示例代码:
```
#include <QWidget>
#include <QtCharts/QChartView>
#include <QtCharts/QBarSeries>
#include <QtCharts/QBarSet>
#include <QtCharts/QValueAxis>
#include <QtCharts/QBarCategoryAxis>
QT_CHARTS_USE_NAMESPACE
class HistogramWidget : public QWidget {
public:
HistogramWidget(QWidget *parent = nullptr) : QWidget(parent) {
QChart *chart = new QChart();
QBarSeries *series = new QBarSeries();
QBarSet *set = new QBarSet("Data");
// 以下为假数据,实际使用时需要修改为真实数据
*set << 1 << 2 << 3 << 4 << 5 << 6 << 7 << 8 << 9 << 10;
series->append(set);
chart->addSeries(series);
chart->setTitle("Histogram");
chart->setAnimationOptions(QChart::SeriesAnimations);
QValueAxis *axisX = new QValueAxis();
axisX->setLabelFormat("%d");
axisX->setTitleText("X Axis");
chart->addAxis(axisX, Qt::AlignBottom);
series->attachAxis(axisX);
QBarCategoryAxis *axisY = new QBarCategoryAxis();
axisY->setTitleText("Y Axis");
chart->addAxis(axisY, Qt::AlignLeft);
series->attachAxis(axisY);
QChartView *chartView = new QChartView(chart);
chartView->setRenderHint(QPainter::Antialiasing);
setCentralWidget(chartView);
}
};
```
在窗口中创建一个HistogramWidget的实例,即可在QWidget上画出一个直方图。
阅读全文