c++qtaccess-violation

Segfault when accessing central widget from slot


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.


Solution

  • In MainWindow::MainWindow:

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

    addWidget() will reparent your LoginPage. After that, its parent is actually a QStackedWidget, and so your MainWindow* cast is wrong in on_loginButton_clicked().