0

I have simple callback functions that provides data to be shown on QT widget main form. As soon breakpoint reaches setText() I have exception Segmentation fault:

void MainWindow::SetAmount(int value)
{
    ui->tbAmount->setText( QString::number(value) );

}

enter image description here

Why I'm geting souch error? When I call SetAmount() from button click it runs fine.

vico
  • 17,051
  • 45
  • 159
  • 315
  • maybe tbAmount is a nullptr? try adding `if (!(ui->tbAmount)) qDebug() << "null";` and see if it prints – JLev May 22 '18 at 13:48

2 Answers2

0

If I had to guess, you're likely attempting to dereference a null pointer. I would add the following error checking to the method to see if this is the case

if (ui == null || ui->tbAmount == null) {
    qDebug() << "NULL Pointer";
}

If either ui or ui->tbAmount is indeed null, I would ensure that they are getting properly initialized elsewhere in your implementation before MainWindow::SetAmount(int value) is called.

hatboyzero
  • 1,929
  • 1
  • 21
  • 44
0

You're invoking the callback from the wrong thread, most likely. It's also possible that you're trying to access it before the object was created (or after it was destructed). Modify as follows:

  1. Value-initialize ui, in spite of whatever you do in the constructor. Hold it by value. Finally - null the ui in the destructor, as a debug aid.

  2. Add checks to the callback.

#if !defined(DEBUG_INIT) && defined(QT_NO_DEBUG)
#define DEBUG_INIT
#elif !defined(DEBUG_INIT) && !defined(QT_NO_DEBUG)
#define DEBUG_INIT = {}
#endif

class MainWindow : public ... {
  Q_OBJECT
  Ui::MainWindow ui DEBUG_INIT; // held by value
  ...
public:
  explicit MainWindow(QWidget *parent = {});
  ~MainWindow() override;
};

MainWindow::MainWindow(QWidget *parent) : baseclass(parent) {
  ui.setupUi(this);
  ...
}

MainWindow::~MainWindow() {
  ...
  Q_UNUSED((ui DEBUG_INIT));
}

void MainWindow::SetAmount(int value) {
  Q_ASSERT(QThread::currentThread() == thread());
  Q_ASSERT(!d_ptr->wasDeleted);
  ui->tbAmount->setText(QString::number(value));
}
Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313