qt 重写继承QGraphicsView类显示直方图和xy坐标以及坐标的箭头
时间: 2023-05-18 08:03:57 浏览: 345
qml-ChartView-直方图显示
好的,这个问题可以回答。以下是一个简单的示例代码,可以在 Qt 中重写继承 QGraphicsView 类来显示直方图和 xy 坐标以及坐标的箭头:
```cpp
#include <QtWidgets>
class HistogramView : public QGraphicsView
{
public:
HistogramView(QWidget *parent = nullptr)
: QGraphicsView(parent)
{
// 设置场景
QGraphicsScene *scene = new QGraphicsScene(this);
setScene(scene);
// 添加直方图
QBarSeries *series = new QBarSeries();
QBarSet *set = new QBarSet("Data");
*set << 1 << 2 << 3 << 4 << 5;
series->append(set);
QChart *chart = new QChart();
chart->addSeries(series);
chart->setTitle("Histogram");
chart->setAnimationOptions(QChart::SeriesAnimations);
QChartView *chartView = new QChartView(chart);
scene->addWidget(chartView);
// 添加坐标箭头
QGraphicsLineItem *xArrow = new QGraphicsLineItem(0, 0, 50, 0);
QGraphicsLineItem *yArrow = new QGraphicsLineItem(0, 0, 0, 50);
QGraphicsTextItem *xLabel = new QGraphicsTextItem("X");
QGraphicsTextItem *yLabel = new QGraphicsTextItem("Y");
xArrow->setPen(QPen(Qt::red, 2));
yArrow->setPen(QPen(Qt::red, 2));
xLabel->setDefaultTextColor(Qt::red);
yLabel->setDefaultTextColor(Qt::red);
xArrow->setTransform(QTransform().translate(50, 0).rotate(90));
yArrow->setTransform(QTransform().translate(0, 50));
xLabel->setPos(50, 0);
yLabel->setPos(0, 50);
scene->addItem(xArrow);
scene->addItem(yArrow);
scene->addItem(xLabel);
scene->addItem(yLabel);
}
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
HistogramView view;
view.show();
return app.exec();
}
```
这个示例代码使用了 Qt 的图表库来显示直方图,使用了 QGraphicsLineItem 和 QGraphicsTextItem 来绘制坐标箭头和标签。
阅读全文