2016-12-04 361 views
2

我想編寫一個程序來自動測試不同屏幕尺寸的網頁尺寸。我使用QWebEngineView創建窗口,我需要模擬用戶鼠標點擊並在網頁中拖放元素。我已經嘗試過qApp-> sendEvent和qApp-> postEvent,但是沒有工作。模擬鼠標點擊QWebEngineView

QMouseEvent *event1 = new QMouseEvent (QEvent::MouseButtonPress, point, 
Qt::LeftButton, 
Qt::LeftButton, 
Qt::NoModifier); 

qDebug() << qApp->sendEvent (driver, static_cast <QEvent *> (event1)); 

QMouseEvent *event2 = new QMouseEvent (QEvent::MouseButtonRelease, point, 
Qt::LeftButton, 
Qt::LeftButton, 
Qt::NoModifier); 

qDebug() << qApp->sendEvent (driver, static_cast <QEvent *> (event2)); 

這兩個類都返回true,但是網頁中的事件沒有被觸發。我需要先關注視圖嗎?它沒有父母,它是一個窗口。沒有更多的圖形元素被使用。 你能幫我嗎?

ps:javascript我不想使用beacause:我無法使用javascript模擬點擊來關注輸入,它沒有任何協調來測試畫布的拖放。

回答

1

看來你必須訪問QWebEngineView的子對象,然後向它發送事件。下面是一個實施鼠標左鍵單擊。您可以更改位置clickPos用於釋放並按模擬拖動。從下面的答案

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?

+1

謝謝!您的解決方案完美運作 –