Important: Please read the Qt Code of Conduct -

Problem with QLineEdit and returnPressedSignal

  • Hi! I would like to share with you a problem that I am having. To simplify I will just paste the code of a test app to show my problem.

    This is a QLineEdit that handles a returnPressed signal calling the SLOT "click()" of a button. When pressed, click() is activated and onButtonClicked is called. Then the UI is deleted and reloaded with a new QLineEdit. Finally, after loading everything it crashes.

    But if I DO NOT PRESS RETURN BUTTON and just click with the mouse on the click button, onButtonClicked is also called and nothing crashes. Elements are deleted and the UI is reloaded correctly.

    I am a little bit lost looking for the solution of my problem.


    #include "mainwindow.h"
    #include "ui_mainwindow.h"
    #include <QLineEdit>

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

    connect(ui->pushButton_next, SIGNAL(clicked(bool)), this, SLOT(onButtonClicked()));


    delete ui;

    void MainWindow::run()
    QHBoxLayout* hLayout = new QHBoxLayout();

    QLineEdit* lineEdit = new QLineEdit();
    connect(lineEdit, SIGNAL(returnPressed()), ui->pushButton_next, SLOT(click()));


    void MainWindow::onButtonClicked()
    QHBoxLayout hLayout = (QHBoxLayout) ui->verticalLayout->itemAt(0);
    QLayoutItem* item = hLayout->takeAt(0);
    QLineEdit lineEdit = (QLineEdit) item->widget();

    delete lineEdit;
    delete item;
    delete hLayout;


  • I answer to myself: use deleteLater() in widgets and layouts.

    Thank's anyway and hope it can help others ;)

Log in to reply