Qt progra crashing when using ui->

  • Hi, so I'm setting up this program with Qt Designer, but for one part I need to be able to control (add and delete) button from the program so I use a QList and I code the widget myself without Qt Designer.

    The thing is when in my code I use ui-> to refer to a widget created with Qt Designer my program crash. Everytime. In every cases. I mean I tried doing basic setGeometry for some widget and as soon as I use ui->ExampleWidget->whateverFunction(); the program crashes on startup with the famous "Stopped responding error"

    @#include "mainwindow.h"
    #include "ui_mainwindow.h"

    MainWindow::MainWindow(QWidget *parent) :
    ui(new Ui::MainWindow)

    void MainWindow::addEmp()
    listEmp.append(new QPushButton("Text Here"));
    thislayout = new QGridLayout;
    thislayout->addWidget(listEmp.back(), 0, 0);

    ui->empWidget->setLayout(thislayout);        //runs fine if I remove this line


    delete ui;
    delete listEmp[0];

    #ifndef MAINWINDOW_H
    #define MAINWINDOW_H

    #include <QMainWindow>
    #include <QtWidgets>

    namespace Ui {
    class MainWindow;

    class MainWindow : public QMainWindow

    explicit MainWindow(QWidget *parent = 0);
    void addEmp();

    Ui::MainWindow *ui;

    QList<QPushButton*> listEmp;
    QGridLayout *thislayout;


    #endif // MAINWINDOW_H

    Thanks a lot guys!

  • Lifetime Qt Champion

    Hi and welcome to devnet,


    The problem is that you are calling addEmploye first. Doing so, ui has not been initialized yet so none of its widgets exists. ui->setupUi(this) must be called first.

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.