PyQt5 QWebEngineView - Issues with Opening Popup Window

65 Views Asked by At

I am developing a PyQt5 application that utilizes QWebEngineView to load an HTML page. The HTML page contains JavaScript code that opens a popup window for entering values. The code works as expected when I open the HTML file in a web browser, but the popup window does not open when loaded in the PyQt5 application.

I suspect that there might be security restrictions or limitations in QWebEngineView that prevent the popup window from opening as intended.

Below is a simplified version of my PyQt5 code:

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>
0

There are 0 best solutions below