我在我的应用程序和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
答案 0 :(得分:5)