关于 Qt场景QGraphicsScene中,添加QWidget窗口,QWidget窗口无法捕捉mouseReleaseEvent松开消息 的解决方法

原博主博客地址:https://blog.csdn.net/qq21497936

需求

        在场景中添加音频和视频窗口,无法触发鼠标松开消息(后续需要做课堂活动、思维导图等等,需要鼠标消息支撑)

 

解决方法

        将QWidget的父类设为当前显示的QGraphicsView或者外部套的QWidget,这样则可以接收到消息。

 

测试代码下载地址

        https://download.csdn.net/download/qq21497936/11256504

 

解决过程

MyWidget为添加的窗口

 

未给添加的窗口设置父类

给添加的窗口设置了父类为外部的Widget

给添加的窗口设置了父类为显示的QGraphicsView

 

设置父类会报错(暂时没有发现有什么影响)

 

原博主博客地址:https://blog.csdn.net/qq21497936

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
QGraphicsScene嵌入QWidget,并支持QWidget之间连线,可以使用QGraphicsProxyWidget类和QGraphicsPathItem类来实现。具体步骤如下: 1. 创建QWidget对象,如QLabel、QPushButton等。 2. 创建QGraphicsProxyWidget对象,将QWidget对象作为参数传入。 3. 将QGraphicsProxyWidget对象添加QGraphicsScene,使用QGraphicsSceneaddItem()方法即可。 4. 创建QGraphicsPathItem对象,使用QGraphicsSceneaddItem()方法将其添加QGraphicsScene。 5. 使用QPainter绘制QGraphicsPathItem对象的路径,路径要连接两个QWidget对象的心点。 6. 在QGraphicsScene重写鼠标事件,监听鼠标按下、移动和释放事件,当鼠标按下时,创建一个QGraphicsPathItem对象,并将其添加QGraphicsScene。当鼠标移动时,更新QGraphicsPathItem对象的路径。当鼠标释放时,判断鼠标释放位置是否在另一个QWidget对象上,如果是,则连接两个QWidget对象。 以下是一个简单的示例代码: ``` QWidget* widget1 = new QLabel("Widget 1"); QGraphicsProxyWidget* proxy1 = new QGraphicsProxyWidget(); proxy1->setWidget(widget1); scene->addItem(proxy1); QWidget* widget2 = new QLabel("Widget 2"); QGraphicsProxyWidget* proxy2 = new QGraphicsProxyWidget(); proxy2->setWidget(widget2); scene->addItem(proxy2); QGraphicsPathItem* pathItem = new QGraphicsPathItem(); scene->addItem(pathItem); void MyScene::mousePressEvent(QGraphicsSceneMouseEvent* event) { if (event->button() == Qt::LeftButton) { pathItem = new QGraphicsPathItem(); pathItem->setPen(QPen(Qt::black, 2)); scene()->addItem(pathItem); pathItem->setZValue(-1); pathItem->setOpacity(0.5); pathItem->setPath(QPainterPath(event->scenePos())); } } void MyScene::mouseMoveEvent(QGraphicsSceneMouseEvent* event) { if (pathItem != nullptr) { QPainterPath path = pathItem->path(); path.lineTo(event->scenePos()); pathItem->setPath(path); } } void MyScene::mouseReleaseEvent(QGraphicsSceneMouseEvent* event) { if (event->button() == Qt::LeftButton) { QList<QGraphicsItem*> items = items(event->scenePos()); foreach(QGraphicsItem* item, items) { if (item == proxy1 || item == proxy2) { QPainterPath path = pathItem->path(); path.lineTo(item->boundingRect().center()); pathItem->setPath(path); break; } } } } ``` 这段代码,MyScene是一个继承自QGraphicsScene的类,重写了鼠标事件widget1和widget2是两个要连接的QWidget对象,proxy1和proxy2是对应的QGraphicsProxyWidget对象。pathItem是一个用于绘制路径的QGraphicsPathItem对象。在鼠标事件,当鼠标按下时,创建一个新的pathItem,并将其添加场景。当鼠标移动时,更新pathItem的路径。当鼠标释放时,判断释放位置是否在另一个QWidget对象上,如果是,则连接两个QWidget对象的心点。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

长沙红胖子Qt(长沙创微智科)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值