Creating a Drop-Down Menu with Qt 4.8

Using the widget QComboBox in Qt 4.8 is pretty easy, but the documentation can be a little bit confusing the first time you want to use it, so here is a quick example on how to use its basic features:

#include <QtGui/QApplication>
#include "mainwindow.h"
int main(int argc, char *argv[])
    QApplication a(argc, argv);
    MainWindow *w = new MainWindow();
    return a.exec();

#include <QtGui/QDialog>
#include <QComboBox>
#include <QLabel>
#include <QGridLayout>

class MainWindow : public QDialog
    MainWindow(QWidget *parent = 0);

    QGridLayout *myGrid;

    QComboBox *myComboBox;
    QLabel *myLabel;
public slots:
    void mySlot(int idx);

#endif // MAINWINDOW_H
#include "mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QDialog(parent)
    myGrid = new QGridLayout(this);
    myLabel = new QLabel("-");
    myComboBox = new QComboBox();
        //we fill myComboBox with some stuff:
        //and we connect the signal to the appropiate slot:
    QObject::connect (myComboBox, SIGNAL(activated(int)), this, SLOT(mySlot(int)));
    myGrid->addWidget(myComboBox, 0, 0, Qt::AlignLeft);
    myGrid->addWidget(myLabel, 1, 0, Qt::AlignLeft);

//The slot that will read our input and do something with it:
void MainWindow::mySlot (int idx)

And now let’s take a look at how this simple example looks:

Default view Dropped menu 2nd option selected

C++ Program Unexpectedly Finished

Error: The program has unexpectedly finished

This is a common error while working with Qt (and C++ in general). You will write some code, compile it without errors or warnings and when you run the application it will crash and throw a “The program has unexpectedly finished.” in the Application Output.

The most common cause of this is using an object you have declared a pointer for but have not allocated.

This piece of code will make the application crash:

QPushButton *myButton;
myGridLayout->addWidget (myButton, 0, 0, Qt::AlignLeft);

But this one won’t:

QPushButton *myButton;
myButton = new QPushButton ("button's text");
myGridLayout->addWidget (myButton, 0, 0, Qt::AlignLeft);

The first example is obviously wrong, but it’s easy to forget the memory allocation when the code starts getting longer.