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.
CODE:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QLineEdit>MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);connect(ui->pushButton_next, SIGNAL(clicked(bool)), this, SLOT(onButtonClicked())); run();
}
MainWindow::~MainWindow()
{
delete ui;
}void MainWindow::run()
{
QHBoxLayout* hLayout = new QHBoxLayout();
ui->verticalLayout->addLayout(hLayout);QLineEdit* lineEdit = new QLineEdit(); hLayout->addWidget(lineEdit); 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();lineEdit->disconnect(); delete lineEdit; delete item; delete hLayout; run();
}
-
I answer to myself: use deleteLater() in widgets and layouts.
Thank's anyway and hope it can help others ;)