Seg Fault After Setting Up New Public Signal in QT

399 views Asked by At

I am just getting my feet wet with Qt, I am trying to pull the string from a QlineEdit and append it to a QTextBrowser after clicking a button(for simplicity/error checking I am just having it append the word appended at the moment).

The program runs, and the GUI gets brought up on the screen, but whenever I click the button, my program seg faults.

Here's my code, I cut a lot out that was unnecessary:

HEADER:

#ifndef TCD2_GUI_H
#define TCD2_GUI_H
//bunch of includes

class TCD2_GUI : public QWidget
{
    Q_OBJECT

public:
     TCD2_GUI(QWidget *window = 0);
     //bunch of other members
     QLineEdit *a1_1;
     QTextBrowser *stdoutput;

public slots:
     void applySettings(void);

private:

};
#endif // TCD2_GUI_H

and here is the snippet of the cpp of which causes the fault

 QTextBrowser *stdoutput = new QTextBrowser();

    stdoutput->append("Welcome!");

    QObject::connect(apply, SIGNAL(clicked()), this, SLOT(applySettings()));

    //------------------------------------------------------Standard Output END
    //layout things

}

void TCD2_GUI::applySettings()
{
    stdoutput->append("appended");
}
2

There are 2 answers

0
Patrice Bernassola On BEST ANSWER

stdoutput in your applySettings() function refer to the member of the TCD2_GUI class whereas stdoutput in your piece of code where the crash happens is a local variable. Try to add in your constructor by example:

stdoutput = new QTextBrowser();

andremove the following line from your piece of code:

QTextBrowser stdoutput = new QTextBrowser();
1
serge_gubenko On

looking at the code provided, my guess would be stdoutput is declared twice. Once as a member of the *TCD2_GUI* class, second time as a local variable in the method (class constructor?) where you do layout. ApplySettings uses a class member which is not initialized, hence segmentation fault.

Changing your code to:

stdoutput = new QTextBrowser();
stdoutput->append("Welcome!");
QObject::connect(apply, SIGNAL(clicked()), this, SLOT(applySettings()));

might fix the problem.

hope this helps, regards