我有以下代码:
from PyQt5 import QtWebEngineWidgets, QtWidgets class Q(QtWebEngineWidgets.QWebEnginePage): pass app = QtWidgets.QApplication([]) l = QtWebEngineWidgets.QWebEngineView() print(type(l.page())) l.setPage(Q(l)) print(type(l.page())) p = Q() l.setPage(p) print(type(l.page())) l.setPage(Q()) print(type(l.page())) app.exec_()这是输出:
<class 'PyQt5.QtWebEngineWidgets.QWebEnginePage'> <class '__main__.Q'> <class '__main__.Q'> <class 'PyQt5.QtWebEngineWidgets.QWebEnginePage'>首先,我创建一个QWebEnginePage派生的Q-class的新实例,将视图设置为其父级并将其指定为视图的页面。 它按预期工作。
接下来我也这样做,但没有给父母。 相反,我创建了一个临时变量,它包含一个新Q并分配它。 它仍然按预期工作。
最后,我直接分配一个动态创建的无父Q.由于某种原因,这不起作用,页面重置为默认类。
为什么会这样?
I have the following code:
from PyQt5 import QtWebEngineWidgets, QtWidgets class Q(QtWebEngineWidgets.QWebEnginePage): pass app = QtWidgets.QApplication([]) l = QtWebEngineWidgets.QWebEngineView() print(type(l.page())) l.setPage(Q(l)) print(type(l.page())) p = Q() l.setPage(p) print(type(l.page())) l.setPage(Q()) print(type(l.page())) app.exec_()And here's the output:
<class 'PyQt5.QtWebEngineWidgets.QWebEnginePage'> <class '__main__.Q'> <class '__main__.Q'> <class 'PyQt5.QtWebEngineWidgets.QWebEnginePage'>
First I create a new instance of the QWebEnginePage-derived Q-class, set the view as its parent and assign it as the view's page. It works as expected.
Next I do the same, but without giving the parent. Instead, I create a temporary variable that holds a new Q and assign it. It still works as expected.
Finally, I directly assign a dynamically created parentless Q. For some reason this doesn't work and the page resets to the default class.
Why does this happen?
最满意答案
QWebEngineView不取得QWebEngineView所有权,也不会重新拥有它。
对于第三个示例,页面没有父级,但它保持活动状态,因为python拥有对它的全局引用。
对于最后一个示例,没有父项,也没有外部引用,因此页面在设置之前会被垃圾收集。 它实际上等同于调用setPage(None) ,它将删除先前设置的页面并恢复默认值。
The QWebEngineView does not take ownership of the QWebEnginePage, and it does not re-parent it.
For the third example, the page has no parent, but it's kept alive because python holds a global reference to it.
For the last example, there is no parent and no external reference, so the page gets garbage-collected before it is set. It is effectively equivalent to calling setPage(None), which will remove the previously set page and restore the default.
更多推荐
发布评论