Unsolved QPushButton pointer randomly becomes null
-
Created a private QPushButton pointer object in my header, and in my constructor I call an Init function which sets my pointer to a new QPushButton, then I add it to an existing grid layout. I proceed to connect my button to a slot I have created,
and that works fine. That slot calls another function which then checks that same pointer variable and somehow now it's set to null.I'm just not sure how it's possible that my button pointer becomes null.
Any ideas?
Thanks.
-
Can you show us your code?
-
// in my header :
QPushButton* buttonPtr;// In Init() called by constructor:
QGridLayout *layout = QWidget::findChild<QGridLayout *>("displayControlGridLayout");
if(layout)
{buttonPtr = new QPushButton("my button");
layout->addWidget(buttonPtr, 1, 1, 1, 1);
connect(buttonPtr, SIGNAL(clicked()),this,SLOT(on_button_clicked()));}
// In my slot:
void MyClass::on_button_clicked()
{
switch_page("Page 1");
}
// switch_pagevoid MyClass::switch_page(QString page)
{
QPushbutton *button;
if(page == "Page 1")
button = buttonPtr;if(button == 0)
{
cout << " Button not found" << std::endl;
}}
// So basically i'm always seeing " Button not found" , but I can confirm that the slot is called prior to this function. -
So that means that
if(page == "Page 1") do not work as you think.have you debug it and tested if page does contain "Page 1" its actually sets
button ?
You compare a QString to a const char * which should work
http://doc.qt.io/qt-5/qstring.html#operator-eq-eq-1But please debug and verify.
-
Well i have other function calls such as switch_page("Page 2");
and they work fine , the only difference is that in switch_page I would have
if(page == "Page 2")
button = QWidget::findChild<QPushButton *>("myButton");so in the first case I was setting button to my "global" pointer buttonPtr, and in this case I'm using
QWidget::findChild.So if(page == "some string")
definitely shouldn't be my issue otherwise if(page == "Page 2")
button = QWidget::findChild<QPushButton *>("myButton"); wouldn't work either. I think it's something to do with buttonPtr. -
can you add
if(buttonPtr) qDebug("It's not a buttonPtr problem");
insideMyClass::switch_page
-
Well just debug it.
place break point at
buttonPtr = new QPushButton("my button");
and in
void MyClass::on_button_clicked()
in the topand see what happens by single stepping.
-
Hmm looks like i wasted all your time. I made a ridiculous mistake and didn't notice that at the start of my switch_page function I had the following( it was someone else's code):
// find the widget for the requested page
widget = QWidget::findChild<QWidget *>(pPage);if (widget == 0) { cout << qPrintable(pPage) << " not found" << std::endl; return; }
facepalm
So if the above code is commented out, then I will have a valid buttonPtr.Sorry everyone and thanks for your help anyway.
-
Hi
That is totally ok. We just hang out here to help people so
its just super you found the actual reason :)