User avatar
mad-hatter
Posts: 419
Joined: Sun Feb 26, 2012 2:58 pm
Location: By the UK seaside

C/C++ Problem with pointers, advice please.

Mon Aug 18, 2014 11:22 am

Hello,

I've got a lot of QGroupBox's on a QMainWindow an am showing a QPushbutton in all of them.
The QPushbutton layout is the same in all QGoupBox's, the only difference is the caption and the slot called.
What I'm trying to do is set up a function to construct the QPushButtons.
I'm having trouble getting the returned QPushButton from the function.
This is due to my lack of knowledge of C++!!!

If I call the function, and omit the return statement, it works as expected.
Rather than trying do it this way, would it be more correct to create a class for the QpushButton?
Any help would and advice would be appreciated.

Regards

Code: Select all

Main form:-
myProg::myProg()
    myNewButton = showStartButton(G9);
    myNewButton->setText("Start");
    QObject::connect(myNewButton, SIGNAL(pressed()), this, slot(mySub()));

Code: Select all

header:-
private:
    QPushButton *myNewButton, *myButton;

Code: Select all

QPushButton myProg::showStartButton(QWidget *parent)
{
    myButton = new QPushButton(parent) ;
    myButton->setGeometry(5,
                          parent->height() - 30,
                          40,
                          24);
    return(myButton);
}

Code: Select all

Error message:-
could not convert '((myProg*(this)->myProg::myButton' from 'QPushButton*' to 'QPushButton'

laurent
Posts: 314
Joined: Thu Jul 26, 2012 11:24 am

Re: C/C++ Problem with pointers, advice please.

Mon Aug 18, 2014 12:10 pm

Hi,
Some remarks :
- Your return value lacks a '*', because it must be a pointer according your requirements : QPushButton * myProg::showStartButton(QWidget *parent).
- At the end of your function, you can simply write "return myButton;".
- Since myButton is a pointer directly used after calling your function, keeping it as an attribute of your class is no longer needed. A local variable could nicely do the job.

Hope it helps.
Regards

User avatar
mad-hatter
Posts: 419
Joined: Sun Feb 26, 2012 2:58 pm
Location: By the UK seaside

Re: C/C++ Problem with pointers, advice please.

Mon Aug 18, 2014 1:12 pm

Hello laurent,

Many thanks, I always have trouble with pointers, can never work it out.
Your explanation helps.

Regards
QPushButton * myProg::showStartButton(QWidget *parent).

Return to “C/C++”