简体   繁体   English

尝试访问对象方法时出现C ++ Qt分段错误

[英]C++ Qt Segmentation fault when trying to access method of an object

I am learning Qt, and I have come up with a problem. 我正在学习Qt,但遇到了问题。 I would like some help, here as I tried changing variables and debugging it, but haven't come up with a solution. 我想要一些帮助,在这里尝试更改变量并对其进行调试,但是还没有提出解决方案。 I'll provide some code to understand the problem i have 我将提供一些代码来了解我遇到的问题

In my ColorButton.h class file 在我的ColorButton.h类文件中

class ColorButton : public QToolButton
{
    Q_OBJECT
 public:
   explicit ColorButton(const QColor &color, QWidget *parent = 0);
   void testMethod();
};

My ColorButton.cpp file is like this 我的ColorButton.cpp文件是这样的

ColorButton::ColorButton(const QColor &color, QWidget *parent)
{
    //some code
}

void ColorButton::testMethod()
{
   //This is
   //a test method
}

I am trying to access this testMethod() from another class. 我试图从另一个类访问此testMethod()。

From this class, header file is Toolbar.h 在此类中,头文件是Toolbar.h

class ToolBar : public QToolBar
{
    Q_OBJECT
public:
    explicit ToolBar(const QMap<ToolsEnum, QAction*> &actionMap, QWidget *parent = 0);

private:
    void setToolbar(); //initialize items
    ColorButton *test; //-----

public slots:
    void setMainColorView();
}

The Toolbar.cpp file is like this Toolbar.cpp文件是这样的

ToolBar::ToolBar(const QMap<ToolsEnum, QAction *> &actionMap, QWidget *parent) :
QToolBar(tr("Tools"),parent), actionMapVar(actionMap)
{
    setToolbar();
}

void ToolBar::setToolbar()
{
  test = new ColorButton(QColor("#8C001A"));
}

void ToolBar::setMainColorView()
{
 test->testMethod();
}
}

The program works when i put test->testMethod(); 当我放入test-> testMethod()时,该程序可以工作; into setToolbar() , but I want to create the object in setToolbar() and call the method in setMainColorView(). 进入setToolbar(),但是我想在setToolbar()中创建对象并在setMainColorView()中调用该方法。

So far I have tried making the Color button variable public, I have also tried initializing the object called test in the constructor, but both don't work. 到目前为止,我已经尝试将“颜色”按钮变量公开,也尝试了在构造函数中初始化名为test的对象,但是两者都不起作用。

Right now, with this code the error I get is "The inferior stopped because it received a signal from the operating system. Signal name: SIGSEGV Signal meaning: Segmentation fault" with an arrow pointing at test->testMethod(). 现在,使用此代码,我得到的错误是“下级停止,因为它收到了来自操作系统的信号。信号名称:SIGSEGV信号含义:分段错误”,带有指向test-> testMethod()的箭头。 I have no clue how to solve it, any help would be appreciated 我不知道如何解决它,任何帮助将不胜感激

I was looking at the wrong place the entire time. 我一直都在看错地方。 I solved this by passing my toolbar object into the class i was calling setMainColorView() from. 我通过将工具栏对象传递给我从中调用setMainColorView()的类中来解决了这一问题。 In that class i made a local variable of the toolbar object, assigned this. 在该类中,我为工具栏对象创建了一个局部变量,并为其分配了该变量。 And then it worked. 然后它起作用了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM