用qt实现点本按钮随机绘制图形的功能画圆,画矩形,画线段,要用qpainter
时间: 2024-12-04 20:23:04 浏览: 50
在Qt中,你可以使用QPainter类来创建并绘制各种图形,包括圆形、矩形和线段。以下是使用QPainter实现这个功能的基本步骤:
1. 创建一个QGraphicsView和QGraphicsScene作为容器,用于显示绘制的图形。
```cpp
QGraphicsView graphicsView;
QGraphicsScene scene(&graphicsView);
```
2. 实现一个类,如CustomShape,继承自QObject,并包含相应的绘图方法:
```cpp
class CustomShape : public QObject {
public:
explicit CustomShape(QPainter* painter, QGraphicsItem::ShapeType type)
: painter(painter), shapeType(type) {}
void paint() {
switch (shapeType) {
case QGraphicsItem::EllipseShape:
painter->drawEllipse(rect());
break;
case QGraphicsItem::RectShape:
painter->drawRect(rect());
break;
case QGraphicsItem::LineShape:
painter->drawLine(start(), end());
break;
}
}
private:
QPainter* painter;
QGraphicsItem::ShapeType shapeType;
QRectF rect(); // 你需要实现矩形区域的方法
QPointF start(), end(); // 根据形状类型定义起点和终点的方法
};
```
3. 在主循环中,每次点击按钮时,动态创建一个CustomShape实例并添加到场景中:
```cpp
connect(button, &QPushButton::clicked, [&]() {
QPainter painter(graphicsView.viewport());
QPoint point = graphicsView.mapToScene鼠标当前位置); // 获取点击位置
CustomShape* shape;
// 生成随机选择的形状类型
int randomType = 随机整数(0, 2);
switch (randomType) {
case 0:
shape = new CustomShape(&painter, QGraphicsItem::EllipseShape);
shape->setPos(point);
break;
case 1:
shape = new CustomShape(&painter, QGraphicsItem::RectShape);
shape->setPos(point);
break;
case 2:
shape = new CustomShape(&painter, QGraphicsItem::LineShape);
// 根据矩形规则设置线段起点和终点
shape->start() = ...; // 设置起点
shape->end() = ...; // 设置终点
break;
}
scene.addItem(shape);
});
```
4. 别忘了清理不再需要的对象:
```cpp
void removeShape(CustomShape* shape) {
scene.removeItem(shape);
delete shape;
}
```
阅读全文
相关推荐



















