Search code examples
c++qtqlineedit

QLineEdit bug in access to its text


please guide me in finding the problem of this simplified code in reading text from qlineedit. My code exit in editUser->text() line. Every thing else is ok when I remove this line.

#include ...
QString USERID_LOG="SomeThing";
logDialog::logDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::logDialog)
{
    ui->setupUi(this);
    QLineEdit* editUser= new QLineEdit( this );
    QPushButton* okButton = new QPushButton(tr("OK"));
    connect(okButton, SIGNAL(clicked()), this,SLOT(okSlot()));
     ...
}
void logDialog::okSlot()
{  USERID_LOG=editUser->text();  //////// Error is here
   logDialog::accept();
   return; }

QString logDialog::GetUser()
{
return(USERID_LOG);
}
////////////////////////////logdialog.h/////////////////////////
QT_BEGIN_NAMESPACE
namespace Ui { class logDialog; }
QT_END_NAMESPACE

class logDialog : public QDialog
{
    Q_OBJECT
 public:
    logDialog(QWidget *parent = nullptr);
    ~logDialog();
     QString GetUser();
 public slots:
    void okSlot();
private:
    QLineEdit* editUser;
    QPushButton* okButton;
    Ui::logDialog *ui;
};

Solution

  • Consider your constructor...

    logDialog::logDialog(QWidget *parent)
        : QDialog(parent)
        , ui(new Ui::logDialog)
    {
        ui->setupUi(this);
        QLineEdit* editUser= new QLineEdit( this );
        QPushButton* okButton = new QPushButton(tr("OK"));
        connect(okButton, SIGNAL(clicked()), this,SLOT(okSlot()));
         ...
    }
    

    The lines...

    QLineEdit* editUser= new QLineEdit( this );
    QPushButton* okButton = new QPushButton(tr("OK"));
    

    redeclare/redefine two locally scoped variables editUser and okButton that shadow the member variables of the same names. Instead you should simply initialize the member variables themselves...

    editUser= new QLineEdit( this );
    okButton = new QPushButton(tr("OK"));
    

    Or, perhaps better, perform the initialization in the ctor's initializer list...

    logDialog::logDialog(QWidget *parent)
        : QDialog(parent)
        , editUser(new QLineEdit(this))
        , okButton(new QPushButton(tr("OK")))
        , ui(new Ui::logDialog)
    {
        ui->setupUi(this);
        connect(okButton, SIGNAL(clicked()), this,SLOT(okSlot()));
        ...