qt 重写继承QGraphicsView类显示直方图和xy坐标以及坐标的箭头使用画笔
时间: 2023-05-18 15:03:59 浏览: 398
可以使用QPainter在QGraphicsView上绘制直方图和坐标轴,具体实现可以参考以下代码:
```
class HistogramView : public QGraphicsView {
public:
HistogramView(QWidget *parent = nullptr) : QGraphicsView(parent) {
setRenderHint(QPainter::Antialiasing);
setScene(new QGraphicsScene(this));
}
void setHistogram(const QVector<int> &data) {
histogramData = data;
update();
}
protected:
void drawForeground(QPainter *painter, const QRectF &rect) override {
Q_UNUSED(rect);
painter->setPen(QPen(Qt::black, 2));
painter->setFont(QFont("Arial", 10));
// 绘制x轴
painter->drawLine(0, height() / 2, width(), height() / 2);
painter->drawLine(width() - 10, height() / 2 - 5, width(), height() / 2);
painter->drawLine(width() - 10, height() / 2 + 5, width(), height() / 2);
painter->drawText(width() - 30, height() / 2 + 20, "x");
// 绘制y轴
painter->drawLine(width() / 2, 0, width() / 2, height());
painter->drawLine(width() / 2 - 5, 10, width() / 2, 0);
painter->drawLine(width() / 2 + 5, 10, width() / 2, 0);
painter->drawText(width() / 2 - 20, 20, "y");
// 绘制直方图
painter->setPen(QPen(Qt::blue, 2));
int barWidth = width() / histogramData.size();
for (int i = 0; i < histogramData.size(); i++) {
int barHeight = histogramData[i] * height() / 100;
painter->drawRect(i * barWidth, height() / 2 - barHeight, barWidth, barHeight);
}
}
private:
QVector<int> histogramData;
};
```
使用方法:
```
HistogramView *view = new HistogramView(this);
QVector<int> data = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
view->setHistogram(data);
```
这样就可以在QGraphicsView上显示直方图和坐标轴了。
阅读全文