red X
red X

Reputation: 15

How to Expose C++ Qt WebView and Window Functions to Python Without Using PySide or PyQt?

I'm working on a project where I need to integrate a Qt6 WebView into Python. The WebView should allow dynamic control from Python, including:

What I Want to Achieve:

Dynamically set window properties (e.g., resize(800, 600), borderless mode, etc.). Load either:

What I’ve Tried:

#include <pybind11/stl.h>
#include <QApplication>
#include <QWebEngineView>
#include <QString>

namespace py = pybind11;

class WebView {
public:
    WebView() {
        int argc = 0;
        char *argv[] = {nullptr};
        app = std::make_unique<QApplication>(argc, argv);
        view = std::make_unique<QWebEngineView>();
    }

    void resize(int width, int height) {
        view->resize(width, height);
    }

    void setHtml(const std::string &html) {
        view->setHtml(QString::fromStdString(html));
    }

    void setUrl(const std::string &url) {
        view->setUrl(QUrl(QString::fromStdString(url)));
    }

    void exec() {
        view->show();
        app->exec();
    }

private:
    std::unique_ptr<QApplication> app;
    std::unique_ptr<QWebEngineView> view;
};

PYBIND11_MODULE(qt_webview, m) {
    py::class_<WebView>(m, "WebView")
        .def(py::init<>())
        .def("resize", &WebView::resize)
        .def("setHtml", &WebView::setHtml)
        .def("setUrl", &WebView::setUrl)
        .def("exec", &WebView::exec);
}
  1. I cannot tweak window styles (e.g., borderless or full-screen). Ubuntu

  2. I can't execute or retrieve JavaScript results from Python.

  3. I feel my approach isn't complete or robust for all the features I need.

Constraints:

Questions:

Environment:

OS:  Windows 10 or Ubuntu 20.04
Qt Version: 6.4.2
Python Version: 3.12
Compiler: g++ with C++17

Any help or suggestions would be greatly appreciated!

Upvotes: 0

Views: 27

Answers (0)

Related Questions