graphicsview框架的交互式K线,给出详细的C/C++代码
时间: 2024-05-09 13:14:24 浏览: 254
以下是一个基于GraphicsView框架实现的交互式K线的C++代码示例:
```cpp
#include <QtWidgets>
#include <cmath>
class KLineChart : public QGraphicsView
{
Q_OBJECT
public:
KLineChart(QWidget *parent = nullptr)
: QGraphicsView(parent)
{
// 设置场景大小
scene = new QGraphicsScene(this);
scene->setSceneRect(0, 0, 800, 600);
setScene(scene);
// 初始化数据
const int dataCount = 100;
for (int i = 0; i < dataCount; ++i) {
qreal x = i * 8;
qreal y = 200 + std::sin(i * M_PI / 10.0) * 100;
data.append(QPointF(x, y));
}
// 绘制K线
drawKLine();
// 启用交互模式
setInteractive(true);
setDragMode(QGraphicsView::ScrollHandDrag);
}
protected:
void wheelEvent(QWheelEvent *event) override
{
// 缩放场景
if (event->modifiers() == Qt::ControlModifier) {
int delta = event->angleDelta().y();
if (delta > 0)
scale(1.2, 1.2);
else if (delta < 0)
scale(1.0 / 1.2, 1.0 / 1.2);
event->accept();
} else {
QGraphicsView::wheelEvent(event);
}
}
void mousePressEvent(QMouseEvent *event) override
{
// 记录初始点
if (event->button() == Qt::LeftButton) {
lastPos = event->pos();
event->accept();
} else {
QGraphicsView::mousePressEvent(event);
}
}
void mouseMoveEvent(QMouseEvent *event) override
{
// 拖动场景
if (event->buttons() & Qt::LeftButton) {
QPointF delta = mapToScene(lastPos) - mapToScene(event->pos());
translate(delta.x(), delta.y());
lastPos = event->pos();
event->accept();
} else {
QGraphicsView::mouseMoveEvent(event);
}
}
private:
void drawKLine()
{
// 计算K线和坐标轴的位置和大小
qreal klineX = 50;
qreal klineY = 50;
qreal klineWidth = scene->width() - 2 * klineX;
qreal klineHeight = scene->height() - 2 * klineY;
qreal xAxisY = klineY + klineHeight * 0.8;
qreal yAxisX = klineX + klineWidth * 0.1;
qreal yAxisWidth = klineWidth * 0.1;
// 绘制坐标轴
QPen axisPen(Qt::gray, 1);
scene->addLine(yAxisX, klineY, yAxisX, xAxisY, axisPen);
scene->addLine(yAxisX + yAxisWidth, klineY, yAxisX + yAxisWidth, xAxisY, axisPen);
scene->addLine(yAxisX, xAxisY, yAxisX + yAxisWidth, xAxisY, axisPen);
// 绘制K线
qreal klineItemWidth = klineWidth / data.count();
QPen klinePen(Qt::black, 1);
for (int i = 0; i < data.count(); ++i) {
QPointF point = data.at(i);
qreal x = klineX + i * klineItemWidth;
qreal y = xAxisY - (point.y() - 200) / 100.0 * klineHeight * 0.6;
qreal height = std::abs(point.y() - 200) / 100.0 * klineHeight * 0.6;
QRectF rect(x, y, klineItemWidth, height);
QGraphicsRectItem *item = scene->addRect(rect, klinePen);
if (point.y() > 200) {
item->setBrush(Qt::red);
} else {
item->setBrush(Qt::green);
}
}
}
private:
QGraphicsScene *scene;
QList<QPointF> data;
QPoint lastPos;
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
KLineChart chart;
chart.show();
return app.exec();
}
#include "main.moc"
```
这个示例实现了一个简单的K线图,通过鼠标拖动和滚轮缩放实现了交互。你可以根据你的需求修改和扩展这个示例。
阅读全文