无法从子类访问 QMainWindow 变量
我正在尝试设置一个可以从主窗口(QMainWindow)级别的多个子项访问的变量。问题是每当我尝试从孩子(或孙子)访问它时,我都会遇到分段错误。
这是所涉及代码的模型:
//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
...
老实说,我不知道我做错了什么。我尝试创建一个新的 MainWindow* 指向父级的指针并对其进行强制转换,我尝试将“global”int 公开并直接访问它,等等。我需要做什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需将 *this 作为构造函数参数传递给
SomeWidget
即可:在稍后实现
SomeWidget
时,您可以通过以下方式访问 MainWindow 的成员:Simply pass *this to
SomeWidget
as a constructor parameter:And than later in implementation of the
SomeWidget
you can access members of MainWindow following way:您可以使用
reinterpret_cast
。请注意,这不是一种安全的方法,因为您可以使指针“指向不兼容类的对象,因此取消引用它是不安全的。”(Info)我刚刚上班,所以我只有时间做一个小(而且丑陋的)例子,一个小的控制台程序。
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.