qt 重写继承QGraphicsView类显示直方图
时间: 2023-05-18 10:03:56 浏览: 111
可以使用QGraphicsScene和QGraphicsRectItem来实现直方图的显示,具体实现可以参考以下代码:
```
class HistogramView : public QGraphicsView {
public:
HistogramView(QWidget *parent = nullptr) : QGraphicsView(parent) {
setScene(new QGraphicsScene(this));
}
void setHistogram(const QVector<int> &data) {
scene()->clear();
int maxValue = *std::max_element(data.constBegin(), data.constEnd());
int barWidth = 20;
int barSpacing = 5;
int x = 0;
for (int value : data) {
int barHeight = (int)(height() * ((double)value / maxValue));
QGraphicsRectItem *bar = new QGraphicsRectItem(x, height() - barHeight, barWidth, barHeight);
bar->setBrush(QBrush(Qt::blue));
scene()->addItem(bar);
x += barWidth + barSpacing;
}
setSceneRect(0, 0, x - barSpacing, height());
}
};
```
使用方法:
```
HistogramView *view = new HistogramView();
view->setHistogram({1, 2, 3, 4, 5});
view->show();
```
这样就可以在窗口中显示一个简单的直方图了。
阅读全文