c++qtsegmentation-faultqtabwidget

segment fault when executing a cpp code using Qt and QTabWidget


im trying to write a qt code using the c++ language. when i reach the QTabWidget part, however, the application crashes without a reason. opening the terminal and i see something like this:

zsh: segmentation fault  Easy-app-Example-16.app/Contents/MacOs/Easy-app-Example-16

using macos, i dunno what it's causing this reason of crashing and 'segmentation faulting'.

here's my code that ive tried so far:

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QMenuBar>
#include <QMenu>
#include <QAction>
class MainWindow:public QMainWindow
{
    Q_OBJECT
public:
    MainWindow(QWidget*parent=nullptr);
private:
    void initialize_window();
    void initialize_tabs();
    void initialize_menus();
    QTabWidget*m_tabs;
    QMenuBar*m_menuBar;
    QMenu*m_fileMenu;
    //...
};

mainwindow.cpp

#include "mainwindow.h"
MainWindow::MainWindow(QWidget*parent)
    : QMainWindow(parent)
{
    initialize_window();
    initialize_tabs();
    initialize_menus();
}
void MainWindow::initialize_window()
{
    QPlainTextEdit*currentTextEditor = qobject_cast<QPlainTextEdit*>m_tabs->currentWidget();
    setWindowTitle(currentTextEditor->toPlainText()); // 'test'
}
void MainWindow::initialize_tabs()
{
    m_tab = new QTabWidget();
    QPlainTextEdit*e;
    e = new QPlainTextEdit();
    e->setText("asdf");
    e->setReadOnly(true);
}
void MainWindow::initialize_menus()
{
    //...
}

im using macos ventura 13.3.1 on arm64 macs. any solution or comments are apprciated, thanks


Solution

  • Adjust your code.

    // ...
    MainWindow::MainWindow(QWidget *parent)
        : QMainWindow(parent)
    {
        initialize_tabs();
        initialize_window();
        initialize_menus();
    }
    // ...
    

    One of the cause of the segmentation error is because of using of undeclared/unallocated variables. From your example, you have first initialize the window before your tab is getting initialized. This results: the program first fires the windows up, but then it discovers that the tab widget has a nullptr with its QTabWidget::currentWidget() because of it's not initialized, allocated, and any widget-inserted. Then, because the nullptr attribute cannot actually do anything, so the zsh throws the segmentational error.