c++ - 将鼠标点击发送到 WebEngineView Qt C++

标签 c++ linux windows qt mouseevent

我正在制作一个 WebAutomation 工具,我想知道如何将鼠标事件发送到 WebEngineView。 以下是我尝试过但没有奏效的一些方法。

event= createMouseEvent(QEvent::MouseButtonPress, QPoint(mouse_x,mouse_y), Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);
QApplication::instance()->sendEvent(view,event);

QTestEventList eventos;
eventos.addMouseClick(Qt::LeftButton, 0, QPoint(mouse_x,mouse_y), -1);
eventos.simulate(view);

view 是一个 QWebEngineView。 我知道可以使用 javascript 方法来单击。但我想为用户提供一种使用鼠标坐标的方法。

我更喜欢跨平台的解决方案(我也在开发该程序的 linux 版本)并且可以在窗口最小化或不在最小化时工作查看。

一个新手友好的解释将不胜感激。 请帮忙。 提前致谢。

最佳答案

看来你必须访问QWebEngineView的一个子对象,然后向它发送事件。下面是它的一个实现。

void LeftMouseClick(QWidget* eventsReciverWidget, QPoint clickPos)
{
    QMouseEvent *press = new QMouseEvent(QEvent::MouseButtonPress,
                                            clickPos,
                                            Qt::LeftButton,
                                            Qt::MouseButton::NoButton,
                                            Qt::NoModifier);
    QCoreApplication::postEvent(eventsReciverWidget, press);
    // Some delay
    QTimer::singleShot(300, [clickPos, eventsReciverWidget]() {
        QMouseEvent *release = new QMouseEvent(QEvent::MouseButtonRelease,
                                                clickPos,
                                                Qt::LeftButton,
                                                Qt::MouseButton::NoButton,
                                                Qt::NoModifier);
        QCoreApplication::postEvent(eventsReciverWidget, release);
    }));
}
QWebEngineView webView = new QWebEngineView();
// You need to find the first child widget of QWebEngineView. It can accept user input events.
QWidget* eventsReciverWidget = nullptr;
foreach(QObject* obj, webView->children())
{
    QWidget* wgt = qobject_cast<QWidget*>(obj);
    if (wgt)
    {
        eventsReciverWidget = wgt;
        break;
    }
}
QPoint clickPos(100, 100);
LeftMouseClick(eventsReciverWidget, clickPos);

借用以下答案Qt WebEngine simulate Mouse Event How to send artificial QKeyEvent to QWebEngineView?

关于c++ - 将鼠标点击发送到 WebEngineView Qt C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38945942/

相关文章:

linux - Perl 更改目录路径的所有权

windows - 如何将命令输出设置为批处理文件中的变量

windows - 最小化应用程序时的 Electron win.flashFrame()方法

c++ - 动态手势的隐马尔可夫模型训练?

c++ - 如何使用 C++ 使用 Lame 将 24 位 wav 转换为 mp3

linux - 在不重新启动 Xorg 的情况下重新加载 XINITRC

linux - 使用 Linux/Vim 将头文件或文本文件信息转换为代码

c - 使用 Windows cmd 作为 visual studio dev cmd

c++ - 查找点积的函数

c++ - ifstream 随机整数?