I have the following snippet:
class A : public QWidget
{
Q_OBJECT
public:
A(QWidget *parent = 0);
void
setGeometry(int x, int y, int w, int h);
protected:
virtual void
resizeEvent(QResizeEvent *event);
}
class B : public A
{
Q_OBJECT
public:
B(A*parent = 0);
void
setGeometry(int x, int y, int w, int h);
protected:
virtual void
resizeEvent(QResizeEvent *event);
}
void
A::setGeometry(int x, int y, int w, int h)
{
QWidget::setGeometry(x, y, w, h);
}
void
A::resizeEvent( QResizeEvent * event)
{
QWidget::resizeEvent(event);
// common A and B stuff
}
void
B::setGeometry(int x, int y, int w, int h)
{
A::setGeometry(x, y, w, h);
}
void
B::resizeEvent( QResizeEvent * event)
{
A::resizeEvent(event);
}
Calling setGeometry on an instance of A will fire resizeEvent() . Invoke setGeometry on an instance of B will not fire resizeEvent(). Is there anything wrong with this?
EDIT:
I could do the same calculation I need inside setGeometry successfully. Now, mine is only curiosity.
There are a few problems with the snippet above, so I’ve altered it in a few places… the code below is the minimum necessary to produce the behaviour you want.
Header:
Implementation:
Changes:
Addition of
Q_OBJECTmacros to class definition:Tells the compiler to add Qt meta-object code for the class (not strictly necessary to ensure that
resizeEvent()s are called, but should be included for objects which inheritQObjectas a matter of course).Addition of constructors which allow the passing in of a parent object and invoke the base class constructor with this parent object AND passing a parent object into the constructors of the two objects when they are created:
From the docs:
If your widgets don’t have parents setting the geometry is half meaningless, as the
xandyparts refer to its position relative to a parent. On top of that, since the widgets have no parents they can’t be visible as part of the application so Qt doesn’t bother to call the appropriateresizeEvent().