QWidget::childAt(pos) 方法 (部分测试,值得深入)

简要:

1. 通过QWidget::childAt(pos) 方法,使用软件来模拟鼠标,点击指定按钮。
2. 自定义的Widget插入到 Ui界面,可能还需要 QWidget* focus = QWidget::focusWidget(); 来获取当前的焦点widget

官方文档:

QWidget *QWidget::childAt(int x, int y) const

Returns the visible child widget at the position (x, y) in the widget's coordinate system. If there is no visible child widget at the specified position, the function returns nullptr.

QWidget *QWidget::childAt(const QPoint &p) const

This is an overloaded function.

Returns the visible child widget at point p in the widget's own coordinate system.

Qt模拟鼠标点击事件

目的是通过坐标模拟鼠标点击事件。

关键函数:QWidget::childAt(pos);

其中pos是相对于QWidget的坐标,坐标一般有两种:全局坐标和相对坐标。通过mapToGlobal()之类的API可以转换.

测试代码:

#include <QMouseEvent>
#include <QEvent>

//-----------------------------

    QPoint pos(252,0);  //
    QWidget* child = this->childAt(pos);
    QMouseEvent *pressEvent, *releaseEvent;
//
    pressEvent = new QMouseEvent(QEvent::MouseButtonPress, QPoint(0, 0), Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);
    releaseEvent = new QMouseEvent(QEvent::MouseButtonRelease, QPoint(0, 0), Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);
//
    QApplication::sendEvent(child, pressEvent);
    QApplication::sendEvent(child, releaseEvent);

通过以上代码,在this指向窗口的pos位置的控件(一般是QPushButton)会接收到clicked()事件。

	//模拟鼠标点击的第二种方法
	QTest::mouseClick(child, Qt::LeftButton, Qt::NoModifier, QPoint(0, 0));

	//发送事件的第二种方法
	QCoreApplication::postEvent(child, pressEvent);
	QCoreApplication::postEvent(child, releaseEvent);

	//获取当前的焦点widget
	QWidget* focus = QWidget::focusWidget();

https://blog.csdn.net/qq_45662588/article/details/121393657

======

关于QWidget::childAt

childAt返回的是 显示在当前QWidget的参数位置的 最顶层的子widget。比如我有下面这样的ui

然后重载右键菜单事件

void ChildAtCheck::contextMenuEvent(QContextMenuEvent * ev)
{
    QWidget* pItem = childAt(ev->pos());
    if(!pItem) return;
    
    qDebug()<<pItem->objectName()<<"   " << pItem->parent()->objectName();
}

在执行过程中,我在不同位置单击右键得到了不同的结果:

"label"     "centralWidget"
"widget_2"     "centralWidget"
"widget"     "widget_2"
"pushButton_3"     "widget_2"
"pushButton"     "widget"
"pushButton_2"     "widget"

可见childat拿到的是参数对应位置的最顶层widget指针(也就是可见的widget),和qt助手里面的解释相符

QWidget * QWidget::childAt(const QPoint & p) const

This is an overloaded function.

Returns the visible child widget at point p in the widget's own coordinate system

所以如果自己写的MyWidget类作为子widget插入到界面中时,不能childAt获取到指针后直接转成MyWidget,而是通过控件层级关系拿到MyWidget对象指针再转

原文:  https://www.cnblogs.com/TheMagicKnights/p/6616945.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值