Ownership issue with QLineEdit, Q[Plain]TextEdit and createStandardContextMenu
Maurizio Berti
maurizio.berti at gmail.com
Fri Nov 14 16:52:00 GMT 2025
It seems there is an issue with the ownership of the QMenu created from the
private QWidgetTextControl by calling createStandardContextMenu of
QPlainTextEdit and QTextEdit (and the QWidgetLineControl for QLineEdit).
The Qt documentation says that the ownership is transferred to the caller,
but this creates some problems in Python if a persistent reference isn't
kept, which is a bit counterintuitive for common PyQt usage, as the menu
parent is the text widget, which is normally enough to make it persistent
even though no Python reference is kept.
This is normally not a problem if the menu is used with exec(), but there
are cases for which popup() is preferred, or when it has to be used to
"import" the existing menu actions for some other reason, because those
actions get deleted as soon as the original menu is.
Even this simple example raises a RuntimeError exception, as the wrapped
menu is immediately deleted:
te = QTextEdit()
for a in te.createStandardContextMenu().actions():
print(a.text())
Interestingly enough, there is a difference here:
>>> te = QTextEdit()
>>> te.createStandardContextMenu().actions()
>>> print(len(te.findChildren(QMenu)))
0
>>> te.createStandardContextMenu()
>>> print(len(te.findChildren(QMenu)))
1
Note that I purposely didn't keep any reference.
I temporarily worked around it by creating a further QMenu and reparenting
all actions, but I suppose I could probably use sip as well.
This doesn't seem to happen with PySide, so I truly believe that this is a
PyQt issue only.
Regards,
MaurizioB
--
È difficile avere una convinzione precisa quando si parla delle ragioni del
cuore. - "Sostiene Pereira", Antonio Tabucchi
http://www.jidesk.net
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://www.riverbankcomputing.com/pipermail/pyqt/attachments/20251114/ed62e186/attachment.htm>
More information about the PyQt
mailing list