I’m trying to set a variable that can be accessed from multiple children at the MainWindow (QMainWindow) level. The issue is whenever I try to access it from a child (or grandchild), I get a segmentation fault.
Here’s a mock up of the involved code:
//MainWindow.h
...
public:
int getVariable();
void setVariable(int i);
...
private:
int globalInt;
SomeWidget *myWidget;
//MainWindow.cpp
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
...
this->globalInt = 10;
myWidget = new SomeWidget();
myWidget->setParent(this);
....
}
int getVariable()
{
return this->globalInt;
}
void setVariable(int i)
{
this->globalInt = i;
}
...
//SomeWidget.cpp
...
int x = (static_cast<MainWindow*>(this->parent()))->getVariable(); //Causes Segfault
...
I honestly have no idea what I’m doing wrong. I’ve tried creating a new MainWindow* pointer to the parent and casting it, I’ve tried making the “global” int public and directly accessing it, etc. etc. Any ideas what I need to do?
You could use
reinterpret_cast. Note that this is not a secure way, because you can make pointers “that point to an object of an incompatible class, and thus dereferencing it is unsafe.” (Info)I just arrived at work so I only had time for a little (and ugly) example, a small console program.