PyQt Web Browser: Focus on the webpage without a mouse click
I am writing an application for an embedded device that has no mouse input. The web browser is very very basic and does not have any buttons, address bar, file bar , etc. For now, it simply just loads a web page. This web page uses javascript to catch key press events for actions.
The problem I am having is that when the browser loads, the key presses are not caught. I have tracked this problem down to what I believe is a focus problem. When the browser loads, it does not have focus until a mouse click occurs on the application. Since I do not have a mouse, that initial click cannot happen.
How can I make sure that the browser application gets focused correctly such that when I launch it from a terminal or script it will gain immediate focus and the key events can happen accordingly?
My code is as follows:
#!/usr/bin/env python
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
app = QApplication(sys.argv)
web = QWebView()
web.showFullScreen()
web.load(QUrl("http://www.google.com"))
sys.exit(app.exec_())
The QWidget.setFocus() did not work, assuming I used it c开发者_JAVA百科orrectly. Any help is appreciated. Thanks
I tried your code on my laptop and the QWebView had focus already - once Google had loaded I could type and my text appeared in the text box.
If it is a focus problem then as QWebView inherits QWidget you can call its setFocus() method. Here is your code with an extra line calling the QWebView's setFocus method once a page has loaded:
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
app = QApplication(sys.argv)
web = QWebView()
web.loadFinished.connect(web.setFocus)
web.showFullScreen()
web.load(QUrl("http://www.google.com/"))
sys.exit(app.exec_())
You can set focus on the main frame:
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
if __name__ == '__main__':
app = QApplication(sys.argv)
web = QWebView()
frame = web.page().mainFrame()
frame.setFocus()
web.showFullScreen()
web.load(QUrl("http://www.google.com"))
sys.exit(app.exec_())
精彩评论