her*_*ass 5 javascript qt qtwebkit qtwebengine
我有一个Qt应用程序,用于启动Webview QWebChannel.
在这些视图中,我有JavaScript做一些事情,以根据屏幕大小定位/调整窗口大小.该screen对象应该提供这种信息.(屏幕文档)
但在我看来QWebEnginePage,在整个加载过程中屏幕对象都是空的.
如果我在一个按钮上放置一个监听器来到screen.height页面上的某个位置,现在它可以工作了.
//js local file called in html head
//screen = {}
document.addEventListener("load", function(event) {
//screen = {}
new QWebChannel(qt.webChannelTransport, function(channel) {
//screen = {}
//stuff
channel.object.myClass.show(function(res){ //Qt function that calls the show() method of the QWebEngineView
//screen = {}
});
});
document.getElementById("myBtn").addEventListener("click", function(){
console.log("height:" + screen.height); // screen: 1440
});
});
Run Code Online (Sandbox Code Playgroud)
所以我的问题是,如何screen在JavaScript中的某个时刻访问值?
我认为目前您正在尝试访问您的screen对象,但它不可用。事实上,您的 HTML 文件将被直接加载,但其他对象,例如 JavaScript 对象/程序或样式表(例如 CSS 文件)将被异步加载。
QWebEnginePage的文档中对此进行了解释:
html 立即加载;外部对象是异步加载的。
因此,当您的页面未加载时,您无法访问此属性。但是,一旦页面加载,您就可以访问它,就像您实际上使用按钮上的侦听器所做的那样。获取这些属性的另一种方法是Q_INVOKABLE在类中定义方法,以便在 C++ 端检索它们(请参阅此答案)。