尝试在Qt中分配无父窗口小部件时的奇怪行为(Odd behavior when trying to assign parentless widget in Qt)

编程入门 行业动态 更新时间:2024-10-26 12:25:02
尝试在Qt中分配无父窗口小部件时的奇怪行为(Odd behavior when trying to assign parentless widget in Qt)

我有以下代码:

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.

更多推荐

本文发布于:2023-07-22 12:12:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1219910.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:部件   分配   奇怪   窗口   Qt

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!