Qt中怎么根据鼠标选择删除东西
时间: 2023-06-12 19:05:20 浏览: 91
在Qt中,可以使用QGraphicsScene和QGraphicsItem来实现鼠标选择并删除图形项的功能。具体步骤如下:
1. 创建一个继承自QGraphicsScene的子类,用于显示图形项并响应鼠标事件。
2. 在子类的构造函数中,设置鼠标跟踪属性和选择模式。例如:
```cpp
MyScene::MyScene(QObject* parent) : QGraphicsScene(parent)
{
setMouseTracking(true);
setSelectionBehavior(QGraphicsScene::SelectItems);
}
```
3. 在子类中重写鼠标事件处理函数,实现选择和删除图形项的逻辑。例如:
```cpp
void MyScene::mousePressEvent(QGraphicsSceneMouseEvent* event)
{
if (event->button() == Qt::LeftButton) {
// 在鼠标点击位置添加一个矩形项
QGraphicsRectItem* rectItem = addRect(event->scenePos().x(), event->scenePos().y(), 50, 50);
rectItem->setFlag(QGraphicsItem::ItemIsSelectable); // 设置图形项可选择
}
else if (event->button() == Qt::RightButton) {
// 删除选择的图形项
QList<QGraphicsItem*> selectedItems = this->selectedItems();
foreach (QGraphicsItem* item, selectedItems) {
removeItem(item);
delete item;
}
}
}
```
这样,在鼠标左键点击时会在当前位置添加一个矩形项,而在鼠标右键点击时会删除选择的图形项。注意,需要设置图形项的ItemIsSelectable标志才能使其可选择。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](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)
![](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)
![](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)
![](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)