Issue
When overriding virtual functions of QtWidgets, in which cases should I call super().__init__()
? And in which cases does its position make a difference?
Example:
class Window(QtWidgets.QMainWindow):
def keyPressEvent(self, event: QtGui.QKeyEvent) -> None:
"""Variant A: Top"""
super().__init__(event)
# my code
def mousePressEvent(self, event: QtGui.QMouseEvent) -> None:
"""Variant B: Bottom"""
# my code
super().__init__(event)
def showEvent(self, event: QtGui.QShowEvent) -> None:
"""Variant C: Without"""
# my code
...
I'm asking this, because I noticed that in my grown code I have all three variants, and I don't notice anything not working or any difference. Are there any general rules or best practices I could/should follow?
Solution
When you call super().__init__(...)
, you are literally invoking the parent classes constructor method. This typically should only be done once for each instance of the child widget in it's own constructor (aka __init__
) method, and should be the very first call made.
For example:
class MyWidget(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
# ....... everything else
In my experience, there shouldn't be any need for it to be called in any other method other than the constructor.
Since your examples are all dealing with events, you might actually be referring to other superclass methods. For example if your widget handles an event, but you would still like to have the even propogated to it's parents then you would call the super().eventmethodname(args)
.
For example:
def mousePressEvent(self, event: QtGui.QMouseEvent) -> None:
"""Variant B: Bottom"""
# ... your code here
super().mousePressEvent(event)
Answered By - Alexander
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.