PDA

View Full Version : Newbie - Confused about the central widget



N3wb
20th September 2009, 04:55
Hi,

I've been reading through the GUI programming with Qt4 and really need help understanding the central widget. Here's my code:



#include <QMainWindow>
#include <QtGui>

class MainWindow : public QMainWindow
{
public:
MainWindow(); // Constructor
};


MainWindow::MainWindow()
{
QSpinBox *spinBox = new QSpinBox;
QVBoxLayout *mainLayout = new QVBoxLayout();
mainLayout->addWidget(spinBox);
this->centralWidget()->setLayout(mainLayout);
}

int main(int argc, char *argv[])
{
QApplication app(argc, argv); // Create application. Arguments as parameters
MainWindow *mainWindow = new MainWindow; // Create the application window
mainWindow->show(); // Show the application window
return app.exec();
}

This is my program simplified, all in one file. Although it compiles just fine, the program will crash upon being run.

I really have been trying to figure out how to do this correctly and would really appreciate if someone could point in the right direction!

Thanks :)

SudaNix
20th September 2009, 06:46
you should first set the central widget because this call
this->centralWidget()

will return 0.

here the fix:


MainWindow::MainWindow()
{
QWidget* widget = new QWidget; // parent widget
QSpinBox *spinBox = new QSpinBox;
//... use any widget you want.

// set the layout
QVBoxLayout *mainLayout = new QVBoxLayout(widget);
mainLayout->addWidget(spinBox);

setCentralWidget(widget);
}