1
votes

I'm creating a simple desktop app with a single window and a navigation based on QStackedWidget as central widget.

Upon starting, the application adds a widget in the QStackedWidget and other widgets are added after user interaction. Unfortunately simply trying to access the QStackedWidget from a widget's slot causes a segfault.

MainWindow.cpp

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
  ui->setupUi(this);
  ui->centralWidget->addWidget(new LoginPage(this)); // centralWidget = QStackedWidget
}

void MainWindow::onLoginSuccess()
{
  qDebug() << ui->centralWidget;
}

LoginPage.cpp slot

void LoginPage::on_loginButton_clicked()
{
  // Check stuff and all

  ((MainWindow*)parent())->onLoginSuccess();
}

The simple debug in onLoginSuccess() results in this error:

Exception at 0x760f92a7, code: 0xc0000005: read access violation at: 0x0, flags=0x0 (first chance)

I have no trouble updating other UI elements from the slot, so I don't know what's wrong here.

1
It seems that parent() is null and you are not checking for that. Is your constructor for LoginPage correctly handling the parent parameter? - drescherjm
Also I would use a signal / slot for this. I mean connect on_loginButton_clicked to MainWindow::onLoginSuccess() instead of a direct call. - drescherjm
parent isn't null, calling the method doesn't fail if I simply debug a string or anything else. As for using signal/slot this would mean putting most of the logic in the MainWindow which doesn't really make sense... - Jukurrpa
The signal slot would be a single connect in your constructor for LoginPage. - drescherjm
@jturcotte 's answer was the right one, but using signal/slots sounds like a nicer solution than casting the parent and calling the method, thanks - Jukurrpa

1 Answers

2
votes

In MainWindow::MainWindow:

  ui->centralWidget->addWidget(new LoginPage(this)); // centralWidget = QStackedWidget

addWidget will reparent your LoginPage. So parent() is actually a QStackedWidget* and your MainWindow* cast is wrong in on_loginButton_clicked.