上下文:我正在创建一个带有自定义屏幕键盘的小型Web浏览器。
它与Qt WebKit(QWeb*
类)的工作几乎没有关系,但是WebKit中存在错误导致的崩溃...在Qt 5.4.0之后将无法修复,因为他们正在转向Qt WebEngine。
所以我决定将这些东西移到Qt WebEngine(QWebEngine*
类),遵循简短的webkit-> webengine过渡指南。在关于QWebElement
的警告部分之后,我一直在展示/隐藏屏幕键盘(现在需要运行异步.JS代码)。但我正在摸索如何将人工关键事件发送到网页。
我试过一些东西:
QCoreApplication::postEvent(m_webview, event)
什么都不做,当它与旧的QWeb
东西一起工作时;谢谢,
我想现在实现这一目标的唯一可能性就是利用QAction
将事件发送到WebView,例如使用类似的东西:
connect( this , SIGNAL( keyPressed( int ) ) , &m_webview , SLOT( handleKey( int ) ) );
我想这个功能将在Qt 5.5.1中添加,如下所示:
尽管最初的问题已经有一年了,但对于那些喜欢我的人来说,它仍然是真实的(最后!)从QWebKit到QWebEngine(Qt 5.5 - 5.6b)。这是一个需要现有webenginepage-> view()的脏解决方案。这适用于鼠标事件,如果它不适用于键盘事件,那就不足为奇了:
void Whatever::sendMouseEvent( QObject* targetObj, QMouseEvent::Type type, const QPoint& pnt ) const
{
QMouseEvent event( type, pnt, Qt::LeftButton, Qt::LeftButton, Qt::NoModifier );
QApplication::sendEvent( targetObj, &event );
}
void Whatever::sendMouseClick( QObject* targetObj, const QPoint& pnt ) const
{
sendMouseEvent( targetObj, QMouseEvent::MouseMove, pnt );
sendMouseEvent( targetObj, QMouseEvent::MouseButtonPress, pnt );
sendMouseEvent( targetObj, QMouseEvent::MouseButtonRelease, pnt );
}
void Whatever::emulateMouseClick( const QPoint& pnt ) const
{
//-- right now (Qt 5.5 & 5.6) there is only one child -
//-- QtWebEngineCore::RenderWidgetHostViewQtDelegateWidget
//-- but it could change in future
Q_FOREACH( QObject* obj, mWebEnPage->view()->children() ) //-- ACHTUNG! Check mWebEnPage->view() in real code!
if( qobject_cast<QWidget*>( obj ) )
sendMouseClick( obj, pnt );
}
灵感来自Using QWebEngine to render an image和How can I get paint events with QtWebEngine?以及谷歌搜索。
这段代码很好用
for(auto* child : ui->webEngineView->children() ) {
int key = Qt::Key_V; //or some other
QKeyEvent pressEvent = QKeyEvent(QEvent::KeyPress, key, Qt::NoModifier, QKeySequence(key).toString());
QKeyEvent releaseEvent = QKeyEvent(QEvent::KeyRelease, key, Qt::NoModifier);
qApp->sendEvent(child, &pressEvent);
qApp->sendEvent(child, &releaseEvent);
}