confusion using 'this' pointer
-
Hi all,
I'm opening a new window upon clicking a push button from a QmainWindow as follows:
void stageProgram::on_pushButton_programKeyGrip_clicked() { this->hide(); keygrip = new ProgramKeyGrip(); //---> here 'this' pointer not passed keygrip -> show(); }
If I dont pass
this
pointer as above, I can see thePaintevent
(drawing two lines in the window) in theProgramKeyGrip
(given below):#include "programkeygrip.h" #include "ui_programkeygrip.h" ProgramKeyGrip::ProgramKeyGrip(QWidget *parent) : QMainWindow(parent) , ui(new Ui::ProgramKeyGrip) { ui->setupUi(this); } ProgramKeyGrip::~ProgramKeyGrip() { delete ui; } void ProgramKeyGrip::paintEvent(QPaintEvent *e) { QPainter painter1(this); QPen linepen1(Qt::darkRed); linepen1.setWidth(2); painter1.setPen(linepen1); painter1.drawLine(p11,p12); painter1.drawLine(p12,p13); }
Where as If I do as follows ,
PaintEvent
is not visible in the new window:void stageProgram::on_pushButton_programKeyGrip_clicked() { this->close(); // or hide() keygrip = new ProgramKeyGrip(this); //---> here 'this' pointer passed keygrip -> show(); }
Any idea, what's happening here?
Thanks in advance
-
Hi,
In your second case, keygrip becomes a child of the
stageProgram
and will thus appear in its hierarchy. Since you are closing or hiding its parent, theres no reason forkeygrip
to be chown. -
@SGaist Thanks for your response.
My doubt is still- how this affects thepaintEvent
in thekeygrip
?keygrip = new ProgramKeyGrip();
--->this casepaintEvent
is visible
keygrip = new ProgramKeyGrip(this);
----> herepaintEvent
not visible (all other widgets are visbile) -
@viniltc said in confusion using 'this' pointer:
keygrip = new ProgramKeyGrip(); --->this case paintEvent is visible
-> not parented so is shown because it ignores the widget were it was created in because it doesn't even know it exists.
@viniltc said in confusion using 'this' pointer:
keygrip = new ProgramKeyGrip(this); ----> here paintEvent not visible (all other widgets are visbile)
Parented to a widget that is hidden so not shown since all the children of said widget will also be hidden.
-
@SGaist Thanks for your response.
My doubt is still- how this affects thepaintEvent
in thekeygrip
?keygrip = new ProgramKeyGrip();
--->this casepaintEvent
is visible
keygrip = new ProgramKeyGrip(this);
----> herepaintEvent
not visible (all other widgets are visbile)@viniltc said in confusion using 'this' pointer:
keygrip = new ProgramKeyGrip(this);
To add to @SGaist, the code above is equivalent to
keygrip = new ProgramKeyGrip(); keygrip->setParent(this);