我正在开发一个 PyQt5 应用程序,它利用 QWebEngineView 加载 HTML 页面。 HTML 页面包含 JavaScript 代码,可打开用于输入值的弹出窗口。当我在 Web 浏览器中打开 HTML 文件时,代码按预期工作,但在 PyQt5 应用程序中加载时,弹出窗口不会打开。
我怀疑 QWebEngineView 中可能存在安全限制或限制,导致弹出窗口无法按预期打开。
下面是我的 PyQt5 代码的简化版本:
import sys
from PyQt5.QtCore import QUrl
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget
class MyWebView(QWebEngineView):
def __init__(self, parent=None):
super(MyWebView, self).__init__(parent)
file_path = r"path\to\index.html"
url = QUrl.fromLocalFile(file_path)
self.load(url)
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.setWindowTitle("Custom Form App")
self.setGeometry(100, 100, 800, 600)
central_widget = QWidget(self)
layout = QVBoxLayout(central_widget)
web_view = MyWebView(self)
layout.addWidget(web_view)
self.setCentralWidget(central_widget)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Custom Form Popup</title>
</head>
<body>
<p>Hello World</p>
<script>
function openPopup(defaultValues = {}) {
return new Promise((resolve) => {
const popupWindow = window.open('', 'Custom Form', `width=${300},height=${200},left=${300},top=${300}`);
const formHTML = `
<div id="customForm">
<label for="speedInput">Speed:</label>
<input type="text" id="speedInput" placeholder="Enter speed" value="${defaultValues.speed || ''}">
<label for="altitudeInput">Altitude:</label>
<input type="text" id="altitudeInput" placeholder="Enter altitude" value="${defaultValues.altitude || ''}">
<button onclick="submitForm()">Submit</button>
</div>
`;
popupWindow.document.write(formHTML);
popupWindow.submitForm = function() {
const speed = popupWindow.document.getElementById('speedInput').value;
const altitude = popupWindow.document.getElementById('altitudeInput').value;
resolve({ speed, altitude });
popupWindow.close();
};
});
}
openPopup({ speed: 50, altitude: 100 })
.then((enteredValues) => {
console.log('Entered Values:', enteredValues);
});
</script>
</body>
</html>
[在此处输入链接描述][1] https://www.rakeshbishnoi.in