Why mousePressEvent() not virtual, but can override it?

  • i inherite a class from QGraphicsView, and simply write a function void mousePressEvent(...), and it works...
    BUT i find that in QGraphicsView, it's also not virtual, just void mousePressEvent(...), so i'm confused why and how it works...

  • Qt Champions 2017

    It is virtual function coming from base class QWidget.

    @virtual void mousePressEvent(QMouseEvent * event)@

    So it is same everywhere. What is confusion ?

  • It is possible to have a function work even if the base function is not virtual. It would help to see the function code. Does it call the original method? Are the arguments the same? More than likely it is simply hiding the old code and since the function exists with the same arguments, the new function takes the place of the inherited function.

    This can cause problems under certain conditions so you should be careful when doing this. For example, if there is a significant part of the original code left out and you don't call the original code (by casting a pointer to the object as the base object and calling the base objects function) then the function may not do everything it is supposed too... causing unwanted side effects.

Log in to reply