使用 javascript 在 Qwebview 中显示选定的文本

displaying selected text in Qwebview using javascript

我正在尝试使用 javascript 在 QwebView 浏览器中显示选定的文本。但我不知道为什么它不起作用.. 这是我的代码:-

frame = self.page().mainFrame().documentElement()
frame.evaluateJavaScript("alert("+"'"+frame.getSelection().toString()+"'"+");")

当我在 运行 这段代码时,它向我显示了错误:-

Traceback (most recent call last):
File "GUI-Test.py", line 32, in slotshowxpath
frame.evaluateJavaScript("alert("+"'"+frame.getSelection().toString()+"'"+");")
AttributeError: 'QWebElement' object has no attribute 'getSelection'

仅仅因为你命名了一个变量frame:

frame = self.page().mainFrame().documentElement()

并不意味着它是一个 QWebFrame:

Each QWebPage object contains at least one frame, the main frame, obtained using QWebPage.mainFrame().

http://pyqt.sourceforge.net/Docs/PyQt4/qwebframe.html

A QWebElement object allows easy access to the document model, represented by a tree-like structure of DOM elements. The root of the tree is called the document element and can be accessed using QWebFrame.documentElement().

http://pyqt.sourceforge.net/Docs/PyQt4/qwebelement.html

如果您查看 QWebElement class,没有名为 getSelection() 的方法。