简要:
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对象指针再转。