The title more or less says it all. I create a widget, add it to QTabWidget and when I switch to the new tab the app crashes.
preferencestab.h (The widget I want to add)
#ifndef PREFERENCESTAB_H
#define PREFERENCESTAB_H
#include <QWidget>
#include "tab.h"
class PreferencesTab : public QWidget
{
Q_OBJECT
public:
explicit PreferencesTab(QWidget *parent = 0);
~PreferencesTab();
int num;
private:
private slots:
};
#endif // PREFERENCESTAB_H
preferencestab.cpp
#include "preferencestab.h"
#include <QDebug>
PreferencesTab::PreferencesTab(QWidget *parent) : QWidget(parent)
{
}
PreferencesTab::~PreferencesTab()
{
}
tabmanager.cpp (subclass of QTabWidget and where I add the new tab)
...
void TabManager::openPreferences()
{
PreferencesTab *pref = new PreferencesTab();
int index = this->addTab(pref, "Edit");
this->setCurrentIndex(index); // It crashes on this line
}
If I remove the line where it crashed it succeeds at creating the new tab but crashes when I manually switch to it.
It must be something stupid but I just can’t find the error. Help Please
Try to debug your application.
In QtCreator, you start the debug mode by pressing F5 (⌘-Y on macs) instead of Ctrl-R. This will launch a debugger (e.g. GDB) which tells QtCreator (which then tells you) what kind of error occurred. You also can set breakpoints, step through your code and inspect the variable values (before the error occures of course).
Another option is to print out the variables using qDebug. Candidates are the
thispointer,prefand theindexvariable; check their values.That said, the problem which causes the crash is most likely outside the
PreferencesTabclass, maybe even outside theTabManagerclass. That the code within a method of a class is executed doesn’t mean that is was a “valid” call (= thethispointer was valid). So checking thethispointer is always a good idea to track calls to null or invalid pointers.If
TabManageris aQObject, even debugging thethispointer will fail (if it is invalid), becauseqDebug() << thiswill ask for themetaObject(), which will be (most likely) an invalid read if thethispointer is invalid.