QWebEngine& QWebChannel:页面重新加载后传输对象`qt.webChannelTransport`消失了

时间:2016-07-15 10:43:29

标签: javascript c++ qt sockets qtwebengine

我在我的应用程序和WebEngine之间创建了一个网络渠道,以便在JavaScript网站上公开QObject但是在重新加载页面后信道丢失或者如果我点击链接到另一个页面。

我想我需要在页面重新加载时重新创建频道,但我没有设法做到这一点。我尝试在页面加载,进度和完成的插槽上执行此操作,但只获得了js: Uncaught ReferenceError: qt is not defined

<!-- language: lang-cpp -->
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    ui->webEngineWidget->load(QUrl("qrc:/index.html"));
    page = ui->webEngineWidget->page();

    channel = new QWebChannel;
    channel->registerObject("external", &exposedObject);
    page->setWebChannel(channel);

    connect(page, &QWebEnginePage::loadStarted, this, &MainWindow::onPageLoadStarted);
    connect(page, &QWebEnginePage::loadProgress, this, &MainWindow::onPageLoadProgress);
    connect(page, &QWebEnginePage::loadFinished, this, &MainWindow::onPageLoadFinished);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::onPageLoadStarted()
{
    qDebug() << "Loading started";
}

void MainWindow::onPageLoadProgress(int progress)
{
    qDebug() << "Loading in progress: " << progress;
}

void MainWindow::onPageLoadFinished()
{
    qDebug() << "Loading finished";
}

使用qwebchannel.js

在页面端创建频道
<h1>Page</h1>
<a href="other.html">Other Page</a>

<script type="text/javascript" src="qrc:///qtwebchannel/qwebchannel.js"></script>
<script>

var webChannel = new QWebChannel(qt.webChannelTransport, function(channel){
    window.external = channel.objects.external;
});

</script>

示例的完整代码在此处:https://github.com/DanmerZ/QWebChannels-example

视频:https://monosnap.com/file/ZTOgj1QH06VRVF3ogmXln07eOVXXCW

P.S。此错误仅适用于Qt5.7,我检查了Qt5.6.1并且通道正常工作。 https://bugreports.qt.io/browse/QTBUG-52209?jql=text%20~%20%22QWebChannel%20reload%22

1 个答案:

答案 0 :(得分:5)