Currently, I want to set value for html using runJavaScript
.
The following code works:
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtWebEngineWidgets import *
class Widget(QWidget):
def __init__(self):
super().__init__()
lay = QVBoxLayout()
self.btn = QPushButton('change html value')
self.browser = QWebEngineView()
lay.addWidget(self.btn)
lay.addWidget(self.browser)
self.setLayout(lay)
self.browser.setHtml(
'''
<html>
<head>
<title>My Page</title>
</head>
<body>
<h1 id="welcome">Welcome to my page!</h1>
<h1 id="value"> 0 </h1>
</body>
</html>
'''
)
self.btn.clicked.connect(self.btnClickSlot)
def btnClickSlot(self, check=False):
self.browser.page().runJavaScript('document.getElementById("value").innerHTML = "1"')
if __name__ == '__main__':
app = QApplication(sys.argv)
win = Widget()
win.show()
app.exec_()
The value changes from 0 to 1 after click the change html value
button.
But, I don't want to trigger the operation by click
. I want to directly change the value.
And the modified code is:
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtWebEngineWidgets import *
class Widget(QWidget):
def __init__(self):
super().__init__()
lay = QVBoxLayout()
self.btn = QPushButton('change html value')
self.browser = QWebEngineView()
lay.addWidget(self.btn)
lay.addWidget(self.browser)
self.setLayout(lay)
self.browser.setHtml(
'''
<html>
<head>
<title>My Page</title>
</head>
<body>
<h1 id="welcome">Welcome to my page!</h1>
<h1 id="value"> 0 </h1>
</body>
</html>
'''
)
self.browser.page().runJavaScript('document.getElementById("value").innerHTML = "1"')
if __name__ == '__main__':
app = QApplication(sys.argv)
win = Widget()
win.show()
app.exec_()
The value don't change as I expect.
How can I directly change the value? Any suggestion is appreciated~~~
):` `page().runJavascript(f"document.getElementById('{_id}').innerHTML", lambda param, id=id: self.store_value(param, id))`. Then just add that argument to the function: `def store_value(self, param, id):`. Note that I used `id` for simplicity, but [`id()`](https://docs.python.org/3/library/functions.html#id) is a builtin python keyword and should not be used as lightly.
– musicamante Feb 25 '23 at 04:01