1

我必须使用 JavaScript 捕获从网页调度的事件,然后将其连接到 MainWindow 类中的插槽。一些接近的东西:

QWebEngineView *view;
view->load(QUrl("https://test.com/"));

connect(view->my_element, &DOMElement::hover, this, &MainWindow::elementHovered);

在 C++ 中最算法的方法是什么?

4

1 回答 1

2

如果要跟踪 DOM 的某些元素的事件并将其通知给 C++ 元素,则必须使用 Qt WebChannel:

#include <QtWebEngineWidgets>

static QString getSourceCode(const QString & filename){
    QFile file(filename);
    if(!file.open(QIODevice::ReadOnly))
        return {};
    return file.readAll();
}

class HoverHelper: public QObject{
    Q_OBJECT
public:
    using QObject::QObject;
Q_SIGNALS:
    void hovered();
public Q_SLOTS:
    void onHovered(){ Q_EMIT hovered(); }
};

#include "main.moc"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    HoverHelper hover_helper;

    QWebChannel channel;
    channel.registerObject("qt_helper", &hover_helper);

    QWebEngineView view;
    view.page()->setWebChannel(&channel);
    QObject::connect(&view, &QWebEngineView::loadFinished, [&view](){
        QStringList source_codes;
        source_codes << getSourceCode(QStringLiteral(":/qtwebchannel/qwebchannel.js"));
        source_codes << R"(
                        new QWebChannel(qt.webChannelTransport, function (channel) {
                            var e = document.getElementById("LearnMore1")
                            e.addEventListener("mouseover", function(){
                                channel.objects.qt_helper.onHovered()
                            });
                        });
                        )";
        view.page()->runJavaScript(source_codes.join("\n"));
        qDebug() << "loadFinished";
    });

    view.resize(640, 480);
    view.load(QUrl("https://test.com/"));
    view.show();

    QObject::connect(&hover_helper, &HoverHelper::hovered, [](){
       qDebug() << "hovered" << QTime::currentTime();
    });
    return a.exec();
}
于 2020-05-13T03:03:29.857 回答