cpp的QGraphicsView画图
时间: 2023-09-06 21:10:56 浏览: 134
在C++中,你可以使用QGraphicsView类来创建一个可视化的绘图窗口。下面是一个简单的示例代码,展示了如何在Qt中使用QGraphicsView来绘制图形:
```cpp
#include <QApplication>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QGraphicsItem>
#include <QPen>
#include <QBrush>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
// 创建场景和视图
QGraphicsScene scene;
QGraphicsView view(&scene);
// 创建一个矩形项
QGraphicsRectItem *rect = new QGraphicsRectItem(0, 0, 100, 100);
rect->setBrush(QBrush(Qt::red)); // 设置填充颜色为红色
rect->setPen(QPen(Qt::black, 2)); // 设置边框颜色为黑色,粗细为2个像素
// 将矩形项添加到场景中
scene.addItem(rect);
// 调整视图的大小以适应场景
view.fitInView(scene.sceneRect(), Qt::KeepAspectRatio);
// 显示视图
view.show();
return a.exec();
}
```
在上面的示例中,我们创建了一个QGraphicsScene对象和一个QGraphicsView对象。然后,我们创建了一个矩形项(QGraphicsRectItem),并将其添加到场景中。我们还设置了矩形项的填充颜色和边框颜色。最后,我们调整了视图的大小以适应场景,并显示了视图。
你可以根据需要添加其他形状(如椭圆、直线、多边形等)以及文本等元素到场景中。希望这对你有所帮助!如果你有任何进一步的问题,请随时提问。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)