Like the title,why the “q_ptr” pointer is assigned to “this” pointer of QObject? in source code.
QObject::QObject(QObjectPrivate &dd, QObject *parent)
: d_ptr(&dd)
{
>>Q_D(QObject);
>>d_ptr->q_ptr = this;/*question*/
.......
Then,when use Q_Q() macro in source code like blow:
Q_Q(QWidget)
It will return the q pointer handled by the function q_fun():
QWidget*q_func() {return static_cast<QWidget*>(q_ptr);}
As all we know,static_castis not safe when cast from parent to child.
I am very frustrated about /*question*/ ,can any guy tell me the secret?Thanks!
This is where the private implementation object (PIMPL idiom) is told about the object it is working for/with (the non-private
QObject). Here’s a good link for info about Qt andd pointers (d_ptr).Q_Qmacro returns the pointer to theQObject, so you can emit signals from it (among other things). As for thestatic_castbit, that is safe because the macro is defined differently for each class created by theQ_DECLARE_PRIVATEandQ_DECLARE_PUBLICmacros: the result being,static_castis always casting to the correct type. Again, I recommend reading the link.